Handling GET and POST in same Flask view

2024/11/19 7:48:00

When I type request.form["name"], for example, to retrieve the name from a form submitted by POST, must I also write a separate branch that looks something like request.form.get["name"]? If I want to support both methods, need I write separate statements for all POST and all GET requests?

@app.route("/register", methods=["GET", "POST"])
def register():"""Register user."""

My question is tangentially related to Obtaining values of request variables using python and Flask.

Answer

You can distinguish between the actual method using request.method.

I assume that you want to:

  • Render a template when the route is triggered with GET method
  • Read form inputs and register a user if route is triggered with POST

So your case is similar to the one described in the docs: Flask Quickstart - HTTP Methods

import flask
app = flask.Flask('your_flask_env')@app.route('/register', methods=['GET', 'POST'])
def register():if flask.request.method == 'POST':username = flask.request.values.get('user') # Your form'spassword = flask.request.values.get('pass') # input namesyour_register_routine(username, password)else:# You probably don't have args at this route with GET# method, but if you do, you can access them like so:yourarg = flask.request.args.get('argname')your_register_template_rendering(yourarg)
https://en.xdnf.cn/q/26467.html

Related Q&A

Overriding inherited properties’ getters and setters in Python

I’m currently using the @property decorator to achieve “getters and setters” in a couple of my classes. I wish to be able to inherit these @property methods in a child class.I have some Python code …

Python Message Box Without huge library dependency

Is there a messagebox class where I can just display a simple message box without a huge GUI library or any library upon program success or failure. (My script only does 1 thing). Also, I only need it …

How to remove the last FC layer from a ResNet model in PyTorch?

I am using a ResNet152 model from PyTorch. Id like to strip off the last FC layer from the model. Heres my code:from torchvision import datasets, transforms, models model = models.resnet152(pretrained=…

Python Twitter library: which one? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, argum…

How do I use url_for if my method has multiple route annotations?

So I have a method that is accessible by multiple routes:@app.route("/canonical/path/") @app.route("/alternate/path/") def foo():return "hi!"Now, how can I call url_for(&q…

Shortest Python Quine?

Python 2.x (30 bytes): _=_=%r;print _%%_;print _%_Python 3.x (32 bytes) _=_=%r;print(_%%_);print(_%_)Is this the shortest possible Python quine, or can it be done better? This one seems to improve o…

How to find all python installations on mac os x and uninstall all but the native OS X installation

I have installed a few versions on my MacBook for different projects and have only now realized what a mistake that was. I have used homebrew to install it, installed it via pythons website (Python 2.7…

Who runs the callback when using apply_async method of a multiprocessing pool?

Im trying to understand a little bit of whats going on behind the scenes when using the apply_sync method of a multiprocessing pool. Who runs the callback method? Is it the main process that called ap…

Difference between hash() and id()

I have two user-defined objects, say a and b. Both these objects have the same hash values. However, the id(a) and id(b) are unequal.Moreover, >>> a is b False >>> a == b TrueFrom th…

get class name for empty queryset in django

I have empty queryset of model Studentstudents = Students.objects.all()If the above queryset is empty, then how can i get the model(class name)?How can i get the model name for empty queryset?EDIT:Ho…