Skip to content

Instantly share code, notes, and snippets.

@volodymyrsmirnov
Created September 5, 2012 08:52
Show Gist options
  • Save volodymyrsmirnov/3633570 to your computer and use it in GitHub Desktop.
Save volodymyrsmirnov/3633570 to your computer and use it in GitHub Desktop.
API
# -*- coding: utf-8 -*-
"""
Router
~~~~~~~~~~~~~~
Routing API requests and errors handling
"""
from flask import Flask, jsonify, request
from api_versions import *
from config import *
app = Flask(__name__)
@app.route('/call/<int:api_version>/<method>', methods=['GET', 'POST'])
def router(api_version, method):
""" Basic routing function for extracting API request parameters and calling method of corresponding API version
Every API method call returns JSON data
* response - error or success
* reason - the caller of API method
* response_type - type of returned data
* data - returned data
"""
API = None
try:
API = __import__("api_versions.api%i" % api_version, globals(), locals(), ['API'], -1).API()
except:
return jsonify(response='error', reason='api_import_error', response_type="str", data="wrong api version %i" % api_version)
if not api_version == API.get_version(None):
return jsonify(response='error', reason='api_versions_mismatch', response_type="str", data="API version mismatch between %i and %i" % (api_version, API.get_version(None)))
if not hasattr(API, method) or not callable(getattr(API, method)):
return jsonify(response='error', reason='api_invalid_method', response_type="str", data="wrong method %s" % method)
try:
response = getattr(API,method)(request.form if request.method == 'POST' else request.args)
response_type = str(type(response).__name__)
return jsonify(response="success", reason="api_call_%i_%s" % (api_version, method), response_type=response_type, data=response)
except Exception as e:
return jsonify(response="error", reason="api_call_%i_%s" % (api_version, method), response_type="str", data=str(e))
@app.errorhandler(404)
def page_not_found(e):
return jsonify(response="error", reason="api_call_unknown", response_type="str", data="API request is invalid")
if __name__ == "__main__":
app.run(debug=CONF_DEBUG)
# -*- coding: utf-8 *-*
"""
API, version 0
~~~~~~~~~~~~~~
Basic API object, implements core functions that should not be replaced in any child classes
"""
from config import *
import psycopg2
class API(object):
"""API, version 0 (core)"""
version = 0
PgDB = None
def __init__(self):
super(API, self).__init__()
def get_version (self, request):
""" Get current API version
:Returns:
api version number, integer
"""
return self.version
def get_server_time (self, request):
""" Get current time on API server
:Returns:
date and time in format 2012-08-26 16:20:07, string
"""
import datetime
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def get_random_uuid (self, request):
""" Generate random UUID
:Returns:
random UUID, string
"""
from uuid import uuid4
return str(uuid4())
def __initDB(self):
""" Initialize PostgreSQL connection """
self.PgDB = psycopg2.connect(host=CONF_DB_HOST, database=CONF_DB_NAME, user=CONF_DB_USER, password=CONF_DB_PASSWORD)
def __del__(self):
if not self.PgDB == None and self.PgDB.closed == 0:
self.PgDB.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment