如何为指定值字段.url在盛满了端点的Flask里

2024-10-04 09:25:59 发布

您现在位置:Python中文网/ 问答频道 /正文

如何定制字段.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",

并按如下方式更改用户字段:

^{pr2}$

当我提交http://127.0.0.1:5000/user/1 像这样抛出错误:

werkzeug.routing.BuildError

BuildError: Could not build url for endpoint '/Users/{id}/Friends' with values ['_sa_instance_state', 'email', 'id', 'nickname', 'password', 'regist_date', 'status']. Did you mean 'version' instead?

有什么建议吗?泰铢

进一步说,如果我改变资源

api.add_resource(User, '/user/<int:userid>', endpoint='userep')

错误消息抛出

werkzeug.routing.BuildError

BuildError: Could not build url for endpoint 'userep' with values ['_sa_instance_state', 'email', 'id', 'nickname', 'password', 'regist_date', 'status']. Did you forget to specify values ['userid']?

正式文件中字段.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)

flask_restful/fields.py


Tags: selfnonehttpurlfieldsistypenot
1条回答
网友
1楼 · 发布于 2024-10-04 09:25:59

我自己回答:这不是解决问题的办法。在

根据flask restful项目问题:api.url_for() fails with endpoints specified by a string和{a2}

代码如下:

from flask import url_for

class ProjectsView(object):
    def __init__(self, projectid):
        self.projectid = projectid
        ...

    def serialize(self):
        return {
            ...
            'tasks_url':url_for('.getListByProjectID', _external=True, projectid=self.projectid),
        }

class Projects(Resource):
    def get(self, userid):
        project_obj_list = []
        ...
        v = ProjectsView(project.id)
        project_obj_list.append(v)

    return jsonify(result=[e.serialize() for e in project_obj_list])

反应是这样的:

^{pr2}$

相关问题 更多 >