DragonOsman

application.py

May 2nd, 2017
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.13 KB | None | 0 0
  1. import os
  2. import re
  3. from flask import Flask, jsonify, render_template, request, url_for
  4. from flask_jsglue import JSGlue
  5.  
  6. from cs50 import SQL
  7. from helpers import lookup
  8.  
  9. # configure application
  10. app = Flask(__name__)
  11. JSGlue(app)
  12.  
  13. # ensure responses aren't cached
  14. if app.config["DEBUG"]:
  15.     @app.after_request
  16.     def after_request(response):
  17.         response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  18.         response.headers["Expires"] = 0
  19.         response.headers["Pragma"] = "no-cache"
  20.         return response
  21.  
  22. # configure CS50 Library to use SQLite database
  23. db = SQL("sqlite:///mashup.db")
  24.  
  25. @app.route("/")
  26. def index():
  27.     """Render map."""
  28.     if not os.environ.get("API_KEY"):
  29.         raise RuntimeError("API_KEY not set")
  30.     return render_template("index.html", key=os.environ.get("API_KEY"))
  31.  
  32. @app.route("/articles")
  33. def articles():
  34.     """Look up articles for geo."""
  35.  
  36.     geo = request.args.get("geo")
  37.     if not geo:
  38.         raise RuntimeError("Location not specified")
  39.    
  40.     geo = lookup(geo)
  41.     return jsonify(geo)
  42.  
  43. @app.route("/search")
  44. def search():
  45.     """Search for places that match query."""
  46.  
  47.     q = request.args.get("q") + "%"
  48.     rows = db.execute("SELECT * FROM places WHERE postal_code LIKE :q OR place_name LIKE :q OR admin_name1 LIKE :q LIMIT 10", q=q)
  49.    
  50.     return jsonify(rows)
  51.  
  52. @app.route("/update")
  53. def update():
  54.     """Find up to 10 places within view."""
  55.  
  56.     # ensure parameters are present
  57.     if not request.args.get("sw"):
  58.         raise RuntimeError("missing sw")
  59.     if not request.args.get("ne"):
  60.         raise RuntimeError("missing ne")
  61.  
  62.     # ensure parameters are in lat,lng format
  63.     if not re.search("^-?\d+(?:\.\d+)?,-?\d+(?:\.\d+)?$", request.args.get("sw")):
  64.         raise RuntimeError("invalid sw")
  65.     if not re.search("^-?\d+(?:\.\d+)?,-?\d+(?:\.\d+)?$", request.args.get("ne")):
  66.         raise RuntimeError("invalid ne")
  67.  
  68.     # explode southwest corner into two variables
  69.     (sw_lat, sw_lng) = [float(s) for s in request.args.get("sw").split(",")]
  70.  
  71.     # explode northeast corner into two variables
  72.     (ne_lat, ne_lng) = [float(s) for s in request.args.get("ne").split(",")]
  73.  
  74.     # find 10 cities within view, pseudorandomly chosen if more within view
  75.     if (sw_lng <= ne_lng):
  76.  
  77.         # doesn't cross the antimeridian
  78.         rows = db.execute("""SELECT * FROM places
  79.            WHERE :sw_lat <= latitude AND latitude <= :ne_lat AND (:sw_lng <= longitude AND longitude <= :ne_lng)
  80.            GROUP BY country_code, place_name, admin_code1
  81.            ORDER BY RANDOM()
  82.            LIMIT 10""",
  83.             sw_lat=sw_lat, ne_lat=ne_lat, sw_lng=sw_lng, ne_lng=ne_lng)
  84.  
  85.     else:
  86.  
  87.         # crosses the antimeridian
  88.         rows = db.execute("""SELECT * FROM places
  89.            WHERE :sw_lat <= latitude AND latitude <= :ne_lat AND (:sw_lng <= longitude OR longitude <= :ne_lng)
  90.            GROUP BY country_code, place_name, admin_code1
  91.            ORDER BY RANDOM()
  92.            LIMIT 10""",
  93.             sw_lat=sw_lat, ne_lat=ne_lat, sw_lng=sw_lng, ne_lng=ne_lng)
  94.  
  95.     # output places as JSON
  96.     return jsonify(rows)
Add Comment
Please, Sign In to add comment