pfwb-archives-proxy/pfwb_archives_proxy/views.py

52 lines
1.7 KiB
Python

import psycopg2
from django.conf import settings
from django.http import HttpResponseRedirect, Http404
def redirect(request, sess, no, nodoc=None, anx=None):
with psycopg2.connect(**settings.TABELLIO_PROCEDURE_DB) as conn:
with conn.cursor() as cur:
query = '''SELECT imageid FROM t_document
WHERE imageid IS NOT NULL
AND sess = %(sess)s
AND no = %(no)s'''
if nodoc:
query += ' AND nodoc = %(nodoc)s'
else:
query += ' AND nodoc IS NULL'
if anx:
query += ' AND anx = %(anx)s'
else:
query += ' AND anx IS NULL'
distinct_types = ('BQR', 'CRI')
type_ = None
for prefix in distinct_types:
if no.startswith(prefix + '-'):
type_, no = no.split('-', 1)
if type_:
query += ' AND type = %(type)s'
else:
query += ' AND type NOT IN %(distinct_types)s'
cur.execute(
query,
{
'sess': sess,
'no': no,
'nodoc': nodoc,
'anx': anx,
'type': type_,
'distinct_types': distinct_types,
},
)
rows = cur.fetchall()
if rows:
url = 'https://archives.pfwb.be/%s' % rows[0][0]
if request.environ.get('QUERY_STRING'):
url += '?%s' % request.environ.get('QUERY_STRING')
return HttpResponseRedirect(url)
raise Http404()