如何在flask-restful中自定义field.url。
user_fields = {
...
'test': fields.Url('userep', absolute=True)
....
}
api.add_resource(User, '/user', '/user/<int:userid>', endpoint='userep')
当我提交http://127.0.0.1:5000/user/1
结果如下:"test": "http://127.0.0.1:5000/user",
并像这样更改user_fields:
user_fields = {
'id': fields.Integer,
'friends': fields.Url('/Users/{id}/Friends'),
当我提交http://127.0.0.1:5000/user/1
时
抛出错误:
werkzeug.routing.BuildError
BuildError:无法为端点'/ Users / {id} / Friends'构建网址 值为''_sa_instance_state','email','id','nickname', 'password','regist_date','status']。你的意思是“版本”吗?
任何建议? THX
进一步,如果我改变资源
api.add_resource(User, '/user/<int:userid>', endpoint='userep')
错误信息抛出
werkzeug.routing.BuildError
BuildError:无法使用值为端点'userep'构建url ['_sa_instance_state','email','id','昵称','密码', 'regist_date','status']。您是否忘记指定值['userid']?
在官方文件field.url
class Url(Raw):
"""
A string representation of a Url
:param endpoint: Endpoint name. If endpoint is ``None``,
``request.endpoint`` is used instead
:type endpoint: str
:param absolute: If ``True``, ensures that the generated urls will have the
hostname included
:type absolute: bool
:param scheme: URL scheme specifier (e.g. ``http``, ``https``)
:type scheme: str
"""
def __init__(self, endpoint=None, absolute=False, scheme=None):
super(Url, self).__init__()
self.endpoint = endpoint
self.absolute = absolute
self.scheme = scheme
def output(self, key, obj):
try:
data = to_marshallable_type(obj)
endpoint = self.endpoint if self.endpoint is not None else request.endpoint
o = urlparse(url_for(endpoint, _external=self.absolute, **data))
if self.absolute:
scheme = self.scheme if self.scheme is not None else o.scheme
return urlunparse((scheme, o.netloc, o.path, "", "", ""))
return urlunparse(("", "", o.path, "", "", ""))
except TypeError as te:
raise MarshallingException(te)
答案 0 :(得分:0)
自己回答:这无法解决问题。
根据烧瓶休息项目问题:api.url_for() fails with endpoints specified by a string和Flask jsonify a list of objects
像这样的代码:{
"result": [
{
...
"tasks_url":"http://127.0.0.1:5000/api/v1.0/1/GetListByProjectID"
}
]
}
和这样的反应:
UISplitViewController