Displaying a form and saving the submited data

Viewed 113

I have a simple app that saves and displays records off of a database,

@user_endpoints.get("/user/<id>")
def get_user(request, id):
    dct = User.by_id(id)
    if not dct:
        return response.json({"Error": "Not Found"}, status=404)
    return response.json(dct.to_dict(), status=200)

When it comes to displaying a user list something like the code below was sufficient,

@user_endpoints.get("/users")
def list_users(request):
    dct = User.all()
    template = template_env.get_template('user_list.html')
    content = template.render(title='User List', users=dct)
    return response.html(content)

The above uses Jinja2 but that is not important to me (this is not a real app). I am not clear on how to display a form for creating a new user and saving the submitted data, can someone provide a simple example for that?

2 Answers

There is no "one way" with Sanic to do that. Sanic does not know about forms. It completely depends on what you do in the frontend, how you encode the data. Are you sending JSON or is it "form-data" encoded? Maybe something completely different?

You would certainly use "POST" instead of "GET" like you did above. You can inspect request and find your data that's been sent from the frontend and then act on it. (Although nowadays you'd start with designing and implementing a proper (REST) API - usually based on JSON - and then use that. The word "form" does not appear here. It's just data.)

Related