最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Flask-restful的api中支持中文

Flask crifan 4529浏览 0评论

之前已经用Flask-restful设计好了对应的api接口

但是只支持英文字符串

如果在POST接口中,传入带中文的JSON字符串时:

{
    “email”: “[email protected]”,
    “facebookUserId”: “157731344684905”,
    “firstName”: “三”,
    “lastName”: “张”,
    “password”: “111111”,
    “phone”: “13711112222”,
    “smsCode”: “891527”
}

就会报错,说无法解析

{
  “message”: {
    “firstName”: “‘ascii’ codec can’t encode character u’\\u4e09′ in position 0: ordinal not in range(128)”
  }
}

如图:

搜:

flask-restful ‘ascii’ codec can’t encode character u’\\u4e09′ in position 0: ordinal not in range(128)

flask-restful ascii codec can’t encode character  in position 0 ordinal not in range(128)

Umlauts in POST requests? · Issue #227 · flask-restful/flask-restful · GitHub

->

说是换成:

type=unicode

或者不指定type,则默认为unicode?

Blog: Encoding and Python: The UnicodeDecodeError exception

然后用unicode:

class RegisterAPI(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument(‘phone’,
                                   type = unicode,
                                   default = “”,
                                   location = ‘json’)
        self.reqparse.add_argument(‘smsCode’,
                                   type = unicode,
                                   default = “”,
                                   location = ‘json’)
        self.reqparse.add_argument(’email’,
                                   type = unicode,
                                   default = “”,
                                   location = ‘json’)
        self.reqparse.add_argument(‘firstName’,
                                   type = unicode,
                                   default = “”,
                                   location = ‘json’)
        self.reqparse.add_argument(‘lastName’,
                                   type = unicode,
                                   default = “”,
                                   location = ‘json’)
        self.reqparse.add_argument(‘password’,
                                   type = unicode,
                                   default = “”,
                                   location = ‘json’)
        self.reqparse.add_argument(‘facebookUserId’,
                                   type = unicode,
                                   default = “”,
                                   location = ‘json’)
        super(RegisterAPI, self).__init__()

就可以用中文注册了:

顺带再去看看:

flask-restful RequestParser add_argument type

看看add_argument的type,到底有哪些类型的值

python – Ascii codec can’t encode character – Stack Overflow

Intermediate Usage — Flask-RESTful 0.2.1 documentation

-》type=int

post_parser.add_argument(
    ’email’, dest=’email’,
    type=email, location=’form’,
    required=True, help=’The user\’s email’,
)
post_parser.add_argument(
    ‘user_priority’, dest=’user_priority’,
    type=int, location=’form’,
    default=1, choices=range(5), help=’The user\’s priority’,
)

其中email是自定义的:

def email(email_str):
    “””Return email_str if valid, raise an exception in other case.”””
    if valid_email(email_str):
        return email_str
    else:
        raise ValueError(‘{} is not a valid email’.format(email_str))

Request Parsing — Flask-RESTful 0.2.1 documentation

-》

parser.add_argument(‘picture’, type=werkzeug.datastructures.FileStorage, location=’files’)

Only use type=list when location=’json’. See this issue for more details

具体的定义:

API Docs — Flask-RESTful 0.2.1 documentation

但是没有更具体的解释:

“type – The type to which the request argument should be converted. If a type raises an exception, the message in the error will be returned in the response. Defaults to unicode in python2 and str in python3.”

不过知道了:

默认是unicode字符串:

python2是unicode

python3是str

python – Parsing a list of integers in flask-restful – Stack Overflow

【总结】

想要让Flask-restful中传入字符串参数支持中文的话,则需要:

设置参数的类型为unicode:

1.默认不设置type,即可默认为unicode

2.如果设置,则指明:type=unicode

<code>class RegisterAPI(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
...
        self.reqparse.add_argument('firstName',
                                   type = unicode,
                                   default = "",
                                   location = 'json')
</code>

3.其它的,目前已知的type,逻辑上是允许任何目前已有的类型,且支持自定义类型

4.目前见过的:

(1)已有类型有:

  • type=str

    • 注:python2中str表示普通字符串

    • 如果是python3,则str表示unicode了,注意不要搞混了。

  • type=unicode

  • type=init

  • type=list, location=“json”

  • type=werkzeug.datastructures.FileStorage

(2)自定义类型有:

<code>def email(email_str):
    """Return email_str if valid, raise an exception in other case."""
    if valid_email(email_str):
        return email_str
    else:
        raise ValueError('{} is not a valid email'.format(email_str))

post_parser.add_argument(
    'email', dest='email',
    type=email, location='form',
    required=True, help='The user\'s email',
)
</code>

转载请注明:在路上 » 【已解决】Flask-restful的api中支持中文

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.160 seconds, using 22.22MB memory