Created
July 10, 2019 08:27
-
-
Save robertusnegoro/d66081c2156e832ad2106fd60207b2bd to your computer and use it in GitHub Desktop.
flask application sample with mysql connection and query inside
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, jsonify | |
import os | |
import pymysql.cursors | |
app = Flask(__name__) | |
MYSQL_HOST = os.getenv('ANFIELD_HOST') | |
MYSQL_USER = os.getenv('ANFIELD_USER') | |
MYSQL_PASS = os.getenv('ANFIELD_PASS') | |
MYSQL_DBN = os.getenv('ANFIELD_DBN') | |
MYSQL_PORT = os.getenv('ANFIELD_PORT', '3306') | |
def player_list(): | |
connection = pymysql.connect( | |
host=MYSQL_HOST, | |
user=MYSQL_USER, | |
password=MYSQL_PASS, | |
db=MYSQL_DBN, | |
port=int(MYSQL_PORT), | |
cursorclass=pymysql.cursors.DictCursor | |
) | |
try: | |
with connection.cursor() as cursor: | |
query_str = "SELECT * FROM players" | |
cursor.execute(query_str) | |
result = cursor.fetchall() | |
finally: | |
connection.close() | |
return result | |
@app.route("/") | |
def index(): | |
return "Hello, this is index" | |
@app.route("/players") | |
def players(): | |
pl = player_list() | |
return jsonify(pl) | |
if __name__ == '__main__': | |
app.run(host="0.0.0.0", port="5050") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment