Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python Flask server for returning names from a MySQL DB
from flask import Flask
from flask import g
from flask import Response
from flask import request
import json
import MySQLdb
app = Flask(__name__)
def db_connect():
g.conn = MySQLdb.connect(host='',
g.cursor = g.conn.cursor()
def db_disconnect(response):
return response
def query_db(query, args=(), one=False):
g.cursor.execute(query, args)
rv = [dict((g.cursor.description[idx][0], value)
for idx, value in enumerate(row)) for row in g.cursor.fetchall()]
return (rv[0] if rv else None) if one else rv
def hello():
return "Hello World!"
@app.route("/names", methods=['GET'])
def names():
result = query_db("SELECT firstname,lastname FROM")
data = json.dumps(result)
resp = Response(data, status=200, mimetype='application/json')
return resp
@app.route("/add", methods=['POST'])
def add():
req_json = request.get_json()
g.cursor.execute("INSERT INTO (firstname, lastname) VALUES (%s,%s)", (req_json['firstname'], req_json['lastname']))
resp = Response("Updated", status=201, mimetype='application/json')
return resp
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.