简体   繁体   中英

python flask post data encoding

I have a flask method which will take post data and do query, code like this

@app.route('/register/search', methods=['POST'])
@cross_origin(origin='*')
def register_search():
    json_data = request.get_json()
    param = {}
    if 'startrow' in request.json:
        param['startrow'] = request.json['startrow']
    if 'endrow' in request.json:
        param['endrow'] = request.json['endrow']
    if 'company_name' in request.json:
        param['company_name'] = request.json['company_name']

I use angular to do a reqest and company_name is 2 chinese character, but param['company_name'] get a string like this '\\xe4\\xb8\\xad\\xe6\\x96\\x87', how can I get original chinese character from param['company_name']

'\\xe4\\xb8\\xad\\xe6\\x96\\x87` looks like utf8 encoded unicode. Try this to convert it back to unicode:

param['company_name'] = request.json['company_name'].decode('utf-8')

I think I got a solution for this:

Wrong I got the posted problem if I use string concat for query like this:

sql = "select * from company where name like " + param['company_name']
cursor.execute(sql)

Correct

sql = "select * from company where name like %s"
cursor.execute(sql,("%"+param['company_name']+"%"))

use prepared statment, it will work

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM