Skip to content

Instantly share code, notes, and snippets.

@easonhan007
Last active October 6, 2023 14:15
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save easonhan007/8134019 to your computer and use it in GitHub Desktop.
Save easonhan007/8134019 to your computer and use it in GitHub Desktop.
A simple app of flask json api
from flask import Flask, jsonify, g, request
from sqlite3 import dbapi2 as sqlite3
DATABASE = './db/test.db'
app = Flask(__name__)
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
db.row_factory = sqlite3.Row
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None: db.close()
def query_db(query, args=(), one=False):
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv
def init_db():
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def add_student(name='test', age=10, sex='male'):
sql = "INSERT INTO students (name, sex, age) VALUES('%s', '%s', %d)" %(name, sex, int(age))
print sql
db = get_db()
db.execute(sql)
res = db.commit()
return res
def find_student(name=''):
sql = "select * from students where name = '%s' limit 1" %(name)
print sql
db = get_db()
rv = db.execute(sql)
res = rv.fetchall()
rv.close()
return res[0]
@app.route('/')
def users():
return jsonify(hello='world')
@app.route('/add',methods=['POST'])
def add_user():
print add_student(name=request.form['name'], age=request.form['age'], sex=request.form['sex'])
return ''
@app.route('/find_user')
def find_user_by_name():
name = request.args.get('name', '')
student = find_student(name)
return jsonify(name=student['name'], age=student['age'], sex=student['sex'])
if __name__ == '__main__' : app.run(debug=True)
@rogerdahl
Copy link

This code is vulnerable to SQL injection attacks. See https://docs.python.org/2/library/sqlite3.html

Usually your SQL operations will need to use values from Python variables. You shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack (see http://xkcd.com/327/ for humorous example of what can go wrong).

Instead, use the DB-API’s parameter substitution. Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor’s execute() method. (Other database modules may use a different placeholder, such as %s or :1.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment