【问题标题】:how to check if an input is either a string or unicode in python如何检查输入是python中的字符串还是unicode
【发布时间】: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


【解决方案1】:

如何在我的 python API 程序中检查某人的输入是字符串还是 unicode:

无需检查

您是在 Python 3 中编写的,所以一开始就没有这种区别 - unicode 不再存在。您只有一种字符串 (str),并且您有字节缓冲区 (bytes),而对于您的问题,bytes 甚至不相关。

看起来你正在使用 Flask? Flask 内部负责解码网络请求。当您询问request.json 时,Flask 已经使用适当的编码在内部对请求进行了解码,并为您提供了一个很好的表示:

  • json 对象的类型为dict
  • json 数组的类型为list
  • json 字符串的类型为 str(我重复一遍 - 已经为你解码)
  • json 数字的类型为int
  • json 空值是None

看到了吗?不bytes,现在不用担心。在处理文件内容等原始数据时,您需要担心bytes

【讨论】:

    【解决方案2】:

    您可以如下检查:

    if isintance(request.json.get('title'), basestring):
        ...
    

    basestring 是 Python 2.7 中 str 和 ucicode 的共同祖先。通过使用 get 而不是 [] 运算符,您甚至可以摆脱 'title' in request.json 检查

    【讨论】:

    • 对不起,我忽略了,您需要 python3 的解决方案。正确答案应该如下:if isintance(request.json.get('title'), str): ...
    • 好的,调用这个 API 的代码会是什么样子?我下面的代码出现 500 错误。 ['code'] import requests url = "localhost:8080/todo/api/v1.0/tasks" payload = '{"title":"Read a book", "description":"Reading..."}' requests.post(url, json=payload) print("完成...") ['代码']
    • 想通了,不需要''
    • 有一个错字“intance”而不是“instance”
    猜你喜欢
    • 2011-06-26
    • 2020-03-20
    • 2015-04-13
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多