drime

French rhyme dictionary with web and CLI interface
git clone https://a3nm.net/git/drime/
Log | Files | Refs | README

drime.py (2167B)


      1 #!/usr/bin/env python3
      2 
      3 import query
      4 from flask import Flask, render_template, request, jsonify
      5 
      6 app = Flask(__name__)
      7 
      8 languages = ['en', 'fr']
      9 
     10 def get_locale():
     11   if request.args.get('lang'):
     12     lang = request.args.get('lang')
     13     if lang in languages:
     14       return lang
     15   return request.accept_languages.best_match(languages)
     16 def get_title():
     17   if get_locale() == 'fr':
     18     return "drime -- dictionnaire de rimes"
     19   else:
     20     return "drime -- French rhyme dictionary"
     21 
     22 @app.route('/')
     23 def root():
     24   return render_template('index.html', title=get_title(), noform=True,
     25       lang=get_locale())
     26 
     27 @app.route('/about')
     28 def about():
     29   return render_template('about.html', title=get_title(), pagesize=query.PAGESIZE,
     30       lang=get_locale())
     31 
     32 @app.route('/query')
     33 def q():
     34   d = {
     35       'q': request.args.get('query').strip().lower(),
     36       'nsyl': request.args.get('nsyl', ""),
     37       'gender': request.args.get('gender', False),
     38       'classical': request.args.get('classical', False),
     39       'page': request.args.get('page'),
     40     }
     41   if not d['page']:
     42     d['page'] = 0
     43   try:
     44     d['page'] = int(d['page'])
     45   except ValueError:
     46     d['page'] = 0
     47   try:
     48     r, count, sure = query.query(**d)
     49     d['lang'] = get_locale()
     50     d['pagesize'] = query.PAGESIZE
     51     d['mode'] = 'query'
     52     d['title'] = get_title()
     53     d['count'] = count
     54     d['sure'] = sure
     55     d['displayed'] = min(d['pagesize'], count)
     56     d['keys'] = r['keys']
     57     if len(r['keys']) == 0:
     58       if request.args.get('json'):
     59         return jsonify(d)
     60       return render_template('notfound.html', **d)
     61     elif len(r['keys']) > 1:
     62       #d['example'] = {}
     63       #for k in d['keys']:
     64         #d['example'][k] = r[k]
     65       if request.args.get('json'):
     66         return jsonify(d)
     67       return render_template('disambig.html', **d)
     68     else:
     69       d['result'] = r['result']
     70       if request.args.get('json'):
     71         return jsonify(d)
     72       return render_template('results.html', **d)
     73   except query.BadValues:
     74     d['mode'] = 'query'
     75     d['lang'] = get_locale()
     76     if request.args.get('json'):
     77       return jsonify(d)
     78     return render_template('error.html', **d)
     79 
     80 if __name__ == '__main__':
     81   app.run()
     82