Receiving User Input
Receiving User Input. In the
action attribute of your
<form> element, you specified that the data of your HTML form should be sent back to the same URL it came from. Now you need to include the functionality to fetch the value in
index(). For this, you need to accomplish two steps. Import Flask’s
request object contains the submitted value and gives you access to it through a Python dictionary syntax. You need to fetch it from the global object to be able to use it in your function. On-screen, you’ll see the code being rewritten to add these two new changes.
request.args dictionary contains any data submitted with an HTTP GET request. If your base URL gets called initially, without a form submission, then the dictionary will be empty and you’ll return an empty string as the default value instead. If the page gets called through submitting the form, then the dictionary will contain a value under the
celsius key, and you can successfully fetch it and add it to the returned string.
01:55 You’re correctly sending and receiving the data that your users are submitting. Before you move on to integrate the submitted value with your temperature converter code, are there any potential problems you can think of with this implementation?
02:24 This is extremely dangerous because your users might accidentally or intentionally break your web app by entering specific types of content. Most of the time, you should allow Flask to take care of these security issues automatically by using a different project setup. However, you’re in this situation now, so it’s a good idea to find out how you can manually make the form you created input safe.
02:49 Taking input from a user and displaying that input back without first investigating what you’re about to display is a huge security hole. Even without malicious intent, your users might do unexpected things that cause your application to break.
03:29 Flask inserts the text directly into HTML code, which causes this text input to get interpreted as HTML tags. Because of that, your browser renders the code dutifully, as it would with any other HTML.
You don’t want to open up the possibility of your users editing aspects of your web app that aren’t meant to be edited. To avoid this, you can use Flask’s built-in
escape(), which converts special HTML characters into equivalent representations that can be displayed safely.
05:04 When building larger web applications, you shouldn’t have to deal with escaping your input since all HTML will be handled using templates. If you want to learn more about that, then check out this Real Python course.
05:20 After learning how to collect user input and also how to escape it, you’re finally ready to implement the temperature conversion functionality and show a user the Fahrenheit equivalent of the Celsius temperature they entered. And that’s what you’ll cover in the next part of the course.
Become a Member to join the conversation.