Advertisement
callyb

pset8 application.py

Apr 29th, 2017
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.25 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. if request.method == "GET":
  36.  
  37. geo = str(request.args.get("geo"))
  38. result = lookup(geo)
  39. return jsonify(result)
  40.  
  41.  
  42. @app.route("/search")
  43. def search():
  44. """Search for places that match query."""
  45.  
  46.  
  47. if request.method == "GET":
  48. q = request.args.get("q") + "%"
  49. rows = db.execute("SELECT * FROM places WHERE postal_code LIKE :q OR place_name LIKE :q OR admin_name1 LIKE :q", q=q)
  50. if not rows:
  51. raise RuntimeError("No such place")
  52. return jsonify(rows)
  53.  
  54.  
  55.  
  56. @app.route("/update")
  57. def update():
  58. """Find up to 10 places within view."""
  59.  
  60. # ensure parameters are present
  61. if not request.args.get("sw"):
  62. raise RuntimeError("missing sw")
  63. if not request.args.get("ne"):
  64. raise RuntimeError("missing ne")
  65.  
  66. # ensure parameters are in lat,lng format
  67. if not re.search("^-?\d+(?:\.\d+)?,-?\d+(?:\.\d+)?$", request.args.get("sw")):
  68. raise RuntimeError("invalid sw")
  69. if not re.search("^-?\d+(?:\.\d+)?,-?\d+(?:\.\d+)?$", request.args.get("ne")):
  70. raise RuntimeError("invalid ne")
  71.  
  72. # explode southwest corner into two variables
  73. (sw_lat, sw_lng) = [float(s) for s in request.args.get("sw").split(",")]
  74.  
  75. # explode northeast corner into two variables
  76. (ne_lat, ne_lng) = [float(s) for s in request.args.get("ne").split(",")]
  77.  
  78. # find 10 cities within view, pseudorandomly chosen if more within view
  79. if (sw_lng <= ne_lng):
  80.  
  81. # doesn't cross the antimeridian
  82. rows = db.execute("""SELECT * FROM places
  83. WHERE :sw_lat <= latitude AND latitude <= :ne_lat AND (:sw_lng <= longitude AND longitude <= :ne_lng)
  84. GROUP BY country_code, place_name, admin_code1
  85. ORDER BY RANDOM()
  86. LIMIT 10""",
  87. sw_lat=sw_lat, ne_lat=ne_lat, sw_lng=sw_lng, ne_lng=ne_lng)
  88.  
  89. else:
  90.  
  91. # crosses the antimeridian
  92. rows = db.execute("""SELECT * FROM places
  93. WHERE :sw_lat <= latitude AND latitude <= :ne_lat AND (:sw_lng <= longitude OR longitude <= :ne_lng)
  94. GROUP BY country_code, place_name, admin_code1
  95. ORDER BY RANDOM()
  96. LIMIT 10""",
  97. sw_lat=sw_lat, ne_lat=ne_lat, sw_lng=sw_lng, ne_lng=ne_lng)
  98.  
  99. # output places as JSON
  100. return jsonify(rows)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement