【发布时间】:2018-05-03 19:41:05
【问题描述】:
如何在我的 python API 程序中检查某人的输入是字符串还是 unicode:
# POST: Add new item to data
# E.G. '{"title":"Read a book", "description":"Reading..."}'
@app.route('/todo/api/v1.0/tasks', methods=['POST'])
def create_task():
if not request.json or not 'title' in request.json:
abort(400)
if 'title' in request.json and type(request.json['title']) != str:
abort(400)
if 'description' in request.json and type(request.json['description']) is not str:
abort(400)
task = {
'id': tasks[-1]['id'] + 1,
'title': request.json['title'],
'description': request.json.get('description', ""),
'done': False
}
tasks.append(task)
return jsonify({'task': [make_public_task(task)]}), 201
必须更改的代码需要是这个位:
if 'title' in request.json and type(request.json['title']) != str:
和
if 'description' in request.json and type(request.json['description']) is not str:
我试过了
not in [str, unicode]:
但这没有用。
有什么想法吗?非常感谢。
【问题讨论】:
-
isinstance(request.json['description'], (str, unicode)). -
你有这个标记为 python-3 但所有字符串在 python 3 中都是 unicode
-
嗨,Willem,它指出:'NameError: name 'unicode' is not defined'
-
@JoeTilsed 那是因为它不是,在 python 3 中,所有字符串文字默认都是 unicode
-
你为什么要区分?如果您担心不是 unicode 的字符串,您可以不用担心,默认情况下它们都是 unicode。如果您需要不是 unicode 的字符串,您可以将它们转换为
str(string, 'utf-8')
标签: python python-3.x api unicode python-unicode