One place for hosting & domains

      Request

      Processing Incoming Request Data in Flask


      In any web app, you’ll have to process incoming request data from users. Flask, like any other web framework, allows you to access the request data easily.

      In this tutorial, we’ll go through how to process incoming data for the most common use cases. The forms of incoming data we’ll cover are: query strings, form data, and JSON objects. To demonstrate these cases, we’ll build a simple example app with three routes that accept either query string data, form data, or JSON data.

      The Request Object

      To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things. Although all the information the request object holds can be useful, in this article, we’ll only focus on the data that is normally directly supplied by the caller of our endpoint.

      To gain access to the request object in Flask, you simply import it from the Flask library.

      from flask import request
      

      You then have the ability to use it in any of your view functions.

      Once we get to the section on query strings, you’ll get to see the request object in action.

      The Example App

      To demonstrate the different ways of using request, we’ll start with a simple Flask app. Even though the example app uses a simple organization layout for the view functions and routes, what you learn in this tutorial can be applied to any method of organizing your views like class-based views, blueprints, or an extension like Flask-Via.

      To get started, first we need to install Flask.

      pip install Flask
      

      Then, we can start with the following code.

      #app.py
      
      from flask import Flask, request #import main Flask class and request object
      
      app = Flask(__name__) #create the Flask app
      
      @app.route('/query-example')
      def query_example():
          return 'Todo...'
      
      @app.route('/form-example')
      def formexample():
          return 'Todo...'
      
      @app.route('/json-example')
      def jsonexample():
          return 'Todo...'
      
      if _name == '__main_':
          app.run(debug=True, port=5000) #run app in debug mode on port 5000
      

      Start the app with:

      python app.py
      

      The code supplied sets up three routes with a message telling us ‘Todo…’. The app will start on port 5000, so you can view each route in your browser with the following links:

      http://127.0.0.1:5000/query-example (or localhost:5000/query-example)
      http://127.0.0.1:5000/form-example (or localhost:5000/form-example)
      http://127.0.0.1:5000/json-example (or localhost:5000/json-example)

      For each of the three routes, you’ll see the same thing:

      Query Arguments

      URL arguments that you add to a query string are the simpliest way to pass data to a web app, so let’s start with them.

      A query string looks like the following:

      example.com?arg1=value1&arg2=value2
      

      The query string begins after the question mark (?) and has two key-value pairs separated by an ampersand (&). For each pair, the key is followed by an equals sign (=) and then the value. Even if you’ve never heard of a query string until now, you have definitely seen them all over the web.

      So in that example, the app receives:

      arg1 : value1
      arg2 : value2
      

      Query strings are useful for passing data that doesn’t require the user to take action. You could generate a query string somewhere in your app and append it a URL so when a user makes a request, the data is automatically passed for them. A query string can also be generated by forms that have GET as the method.

      To create our own query string on the query-example route, we’ll start with this simple one:

      http://127.0.0.1:5000/query-example?language=Python

      If you run the app and navigate to that URL, you’ll see that nothing has changed. That’s only because we haven’t handled the query arguments yet.

      To do so, we’ll need to read in the language key by using either request.args.get('language') or request.args['language'].

      By calling request.args.get('language'), our application will continue to run if the language key doesn’t exist in the URL. In that case, the result of the method will be None. If we use request.args['language'], the app will return a 400 error if language key doesn’t exist in the URL. For query strings, I recommend using request.args.get() because of how easy it is for the user to modify the URL. If they remove one of the keys, request.args.get() will prevent the app from failing.

      Let’s read the language key and display it as output. Modify with query-example route the following code.

      @app.route('/query-example')
      def query_example():
          language = request.args.get('language') #if key doesn't exist, returns None
      
          return '''<h1>The language value is: {}</h1>'''.format(language)
      

      Then run the app and navigate to the URL.

      As you can see, the argument from the URL gets assigned to the language variable and then gets returned to the browser. In a real app, you’d probably want to do something with the data other than simply return it.

      To add more query string parameters, we just append ampersands and the new key-value pairs to the end of the URL. So an additional pair would look like this:

      http://127.0.0.1:5000/query-example?language=Python&framework=Flask

      With the new pair being:

      framework : Flask
      

      And if you want more, continue adding ampersands and key-value pairs. Here’s an example:

      http://127.0.0.1:5000/query-example?language=Python&framework=Flask&website=Scotch

      To gain access to those values, we still use either request.args.get() or request.args[]. Let’s use both to demonstrate what happens when there’s a missing key. We’ll assign the value of the results to variables and then display them.

      @app.route('/query-example')
      def query_example():
          language = request.args.get('language') #if key doesn't exist, returns None
          framework = request.args['framework'] #if key doesn't exist, returns a 400, bad request error
          website = request.args.get('website')
      
          return '''<h1>The language value is: {}</h1>
                    <h1>The framework value is: {}</h1>
                    <h1>The website value is: {}'''.format(language, framework, website)
      

      When you run that, you should see:

      If you remove the language from the URL, then you’ll see that the value ends up as None.

      If you remove the framework key, you get an error.

      Now that you undertand query strings, let’s move on to the next type of incoming data.

      Form Data

      Next we have form data. Form data comes from a form that has been sent as a POST request to a route. So instead of seeing the data in the URL (except for cases when the form is submitted with a GET request), the form data will be passed to the app behind the scenes. Even though you can’t easily see the form data that gets passed, your app can still read it.

      To demonstrate this, modify the form-example route to accept both GET and POST requests and to return a simple form.

      @app.route('/form-example', methods=['GET', 'POST']) #allow both GET and POST requests
      def form_example():
          return '''<form method="POST">
                        Language: <input type="text" name="language"><br>
                        Framework: <input type="text" name="framework"><br>
                        <input type="submit" value="Submit"><br>
                    </form>'''
      

      Running the app results in this:

      The most important thing to know about this form is that it performs a POST request to the same route that generated the form. The keys that we’ll read in our app all come from the “name” attributes on our form inputs. In our case, language and framework are the names of the inputs, so we’ll have access to those in our app.

      Inside the view function, we need to check if the request method is GET or POST. If it’s GET, we simply display the form we have. If it’s POST, then we want to process the incoming data.

      To do that, let’s add a simple if statement that checks for a POST request. If the request method isn’t POST, then we know it’s GET, because our route only allows those two types of requests. For GET requests, the form will be generated.

      @app.route('/form-example', methods=['GET', 'POST']) #allow both GET and POST requests
      def form_example():
          if request.method == 'POST': #this block is only entered when the form is submitted
              return 'Submitted form.'
      
          return '''<form method="POST">
                        Language: <input type="text" name="language"><br>
                        Framework: <input type="text" name="framework"><br>
                        <input type="submit" value="Submit"><br>
                    </form>'''
      

      Inside of the block, we’ll read the incoming values with request.args.get('language') and request.form['framework']. Remember that if we have more inputs, then we can read additional data.

      Add the additional code to the form-example route.

      @app.route('/form-example', methods=['GET', 'POST']) #allow both GET and POST requests
      def form_example():
          if request.method == 'POST':  #this block is only entered when the form is submitted
              language = request.form.get('language')
              framework = request.form['framework']
      
              return '''<h1>The language value is: {}</h1>
                        <h1>The framework value is: {}</h1>'''.format(language, framework)
      
          return '''<form method="POST">
                        Language: <input type="text" name="language"><br>
                        Framework: <input type="text" name="framework"><br>
                        <input type="submit" value="Submit"><br>
                    </form>'''
      

      Try running the app and submitting the form.

      Similiar to the query string example before, we can use request.form.get() instead of referencing the key directly with request.form[]. request.form.get() returns None instead of causing a 400 error when the key isn’t found.

      As you can see, handling submitted form data is just as easy as handling query string arguments.

      JSON Data

      Finally, we have JSON data. Like form data, it’s not so easy to see. JSON data is normally constructed by a process that calls our route. An example JSON object looks like this:

      {
          "language" : "Python",
          "framework" : "Flask",
          "website" : "Scotch",
          "version_info" : {
              "python" : 3.4,
              "flask" : 0.12
          },
          "examples" : ["query", "form", "json"],
          "boolean_test" : true
      }
      

      As you can see with JSON, you can pass much more complicated data that you could with query strings or form data. In the example, you see nested JSON objects and an array of items. With Flask, reading all of these values is straightforward.

      First, to send a JSON object, we’ll need a program capable of sending custom requests to URLs. For this, we can use an app called Postman.

      Before we use Postman though, change the method on the route to accept only POST requests.

      @app.route('/json-example', methods=['POST']) #GET requests will be blocked
      def json_example():
          return 'Todo...'
      

      Then in Postman, let’s do a little set up to enable sending POST requests.

      In Postman, add the URL and change the type to POST. On the body tab, change to raw and select JSON (application/json) from the drop down. All this is done so Postman can send JSON data properly and so your Flask app will understand that it’s receiving JSON.

      From there, you can copy the example into the text input. It should look like this:

      To test, just send the request and you should get ‘Todo…’ as the response because we haven’t modified our function yet.

      To read the data, first you must understand how Flask translates JSON data into Python data structures.

      Anything that is an object gets converted to a Python dict. {"key" : "value"} in JSON corresponds to somedict['key'], which returns a value in Python.

      An array in JSON gets converted to a list in Python. Since the syntax is the same, here’s an example list: [1,2,3,4,5]

      Then the values inside of quotes in the JSON object become strings in Python. true and false become True and False in Python. Finally, numbers without quotes around them become numbers in Python.

      Now let’s get on to reading the incoming JSON data.

      First, let’s assign everything from the JSON object into a variable using request.get_json().

      req_data = request.get_json()
      

      request.get_json() converts the JSON object into Python data for us. Let’s assign the incoming request data to variables and return them by making the following changes to our json-example route.

      @app.route('/json-example', methods=['POST']) #GET requests will be blocked
      def json_example():
          req_data = request.get_json()
      
          language = req_data['language']
          framework = req_data['framework']
          python_version = req_data['version_info']['python'] #two keys are needed because of the nested object
          example = req_data['examples'][0] #an index is needed because of the array
          boolean_test = req_data['boolean_test']
      
          return '''
                 The language value is: {}
                 The framework value is: {}
                 The Python version is: {}
                 The item at index 0 in the example list is: {}
                 The boolean value is: {}'''.format(language, framework, python_version, example, boolean_test)
      

      If we run our app and submit the same request using Postman, we will get this:

      Note how you access elements that aren’t at the top level. ['version']['python'] is used because you are entering a nested object. And ['examples'][0] is used to access the 0th index in the examples array.

      If the JSON object sent with the request doesn’t have a key that is accessed in your view function, then the request will fail. If you don’t want it to fail when a key doesn’t exist, you’ll have to check if the key exists before trying to access it. Here’s an example:

      language = None
      if 'language' in req_data:
          language = req_data['language']
      

      Conclusion

      You should now understand how to use the request object in Flask to get the most common forms of input data. To recap, we covered:

      • Query Strings
      • Form Data
      • JSON Data

      With this knowledge, you’ll have no problem with any data that users throw at your app!

      Learn More

      If you like this tutorial and want to learn more about Flask from me, check out my free Intro to Flask video course at my site Pretty Printed, which takes you from knowing nothing about Flask to building a guestbook app. If that course isn’t at your level, then I have other courses on my site that may interest you as well.



      Source link

      Hacktoberfest: How to Submit Your First Pull Request on Github


      Introduction

      Hacktoberfest is a month-long celebration of open source software, run by DigitalOcean and open to everyone in our global community. To participate, you’ll need to submit four quality pull requests to public GitHub repositories in the month of October. Upon completing the challenge, you’ll earn special prizes, including an exclusive Hacktoberfest t-shirt.

      You can sign up anytime between October 1 and October 31, and we encourage you to connect with other developers and Hacktoberfest enthusiasts for virtual events and information sessions, starting in September.

      In this tutorial we’ll introduce you to Git, the version control system that you’ll use to submit your pull request, and Github, the repository hosting service that we’ll be using to track your progress. By the end of this tutorial, you’ll be ready to submit your first pull request and will be well on your way to participating in Hacktoberfest!

      Version Control

      Before we begin with Git and Github, let’s talk about version control. When developers work on a project together, oftentimes they’ll need to work on the same code base. While they’re working, each developer needs to know about what changes the other developer made, so as not to duplicate work or write code over what has already been done.

      A version control system serves as a saving program for code, where it assigns a version to a project and tracks changes made over time to each file in the project. In this way, developers can work together on a project by checking in with the latest version, to see the changes made before working on their portion of the project’s code.

      Git and Github

      Git, a version control system used to manage developer projects of all sizes, was created in 2005 by Linus Torvalds, the creator of Linux, to help developers contribute code and share code revisions in a way that was fast, efficient, and inexpensive. Git enables developers to edit, share, and publish code, facilitating collaboration and teamwork.

      Github is a cloud-based git repository hosting service that allows developers to take code that they’ve written on their local machines and share it with the world. It provides a way to share the version-tracked projects on your local computer publicly through repositories, or central file storage locations, and depending on the project’s availability (it can be either a public or private repository), other developers can download the project to edit the code, provide insight, and more.

      To get started with Github, you can create an account at Github. For more details on how to do that, please refer to the Hacktoberfest resources page.

      Cloning a Repository

      We’ll now clone and edit our first Github repository. First, let’s navigate to the repository that we’d like to clone. For the sake of this tutorial, we’ll use the Cloud Haiku repository.
      Before you clone this repository, that is, take a copy of the code on Github onto your local machine, you’ll need to take a copy of the whole repository into your own Github account. This is called a fork of the repository, and it allows you to develop your code without affecting the main code base.

      To fork a repository, click the Fork button at the top right in the repository. To clone, click the code button, take a copy of the link provided, then watch as Github takes this repository and adds it as a copy to your account. Your name should now appear as the creator of this repository, which is a ‘fork’ of the main haiku repository.

      Clone the repository

      Next, navigate to your command line interface to clone the project on your local machine.You can do that with the git clone command, which will clone, or copy, the fork that I just created from the haiku repository down to my local machine. This will enable you to make changes to the codebase locally (on your own machine).

      • cd ~
      • git clone https://github.com/sammy/cloud_haiku

      Editing Code Content

      You now have a copy of the Cloud Haiku repository on your local machine, so you’re ready to prepare your contribution. Using the command line interface, navigate to the folder of your cloned repository. If you followed along, you should have a cloud_haiku folder inside your home directory:

      There’s a number of text editors and Integrated Development Environments (IDEs) that you can use to edit your code. IDEs are typically segmented by programming language and include a series of helpful features to streamline the process of developing an application in that language. If you don’t have an IDE currently set up within your work machine, consider checking out Hacktoberfest’s resources page for advice on how to choose an IDE.

      It’s important to take the time to read and understand how the project is organized and the contribution guidelines, and find parts of the code that you can work on. Read any associated documentation provided before making changes. Next, let’s submit a haiku!

      Browse the Codebase

      Adding Content to the Remote Repository

      Now that we have a change made to the haiku repository, we’ll need to track and save that change. The first step in tracking your change is to add it to the version you’re working on. To do that, we’ll execute the command git add . :

      Writing the command in this way allows you to add all changes made to the repository, across files. If you need to only submit changes to an individual file, use git add filename:

      After running the add command, you’ll get no confirmation. To see if your changes have been included in the list of files that is ready to be committed, you can execute the command git status:

      This allows you to check on the status of your tracked changes — you’ll see that your file has been added, but not committed as a change. Git provides this step in the event that you need to amend a change before officially tracking it as new or edited code.

      Git Add

      Next, let’s commit our change. Execute the command git commit, and add a message so that other developers who are collaborating on this project will know about the changes you’ve made:

      • git commit -m "added sammy haiku"

      Writing your commit with a message allows developers to be informed of changes that are made — this message is tracked along with a commit ID and your username.

      Git Commit

      After committing, we’ll need to push changes from our local machine to the remote repository on Github. To do this, let’s execute the command git push:

      Here, we can designate an origin for the push — in this instance, we want our contributions to go to our forked version of DigitalOcean’s haiku repository.

      Git Push

      To recap, so far we’ve identified a repository that we’d like to edit, and took a copy of the repository into our Github account and local machine using fork and clone. We made a change, and submitted our change with git add. We then solidified our change by running git commit, which committed the change. git push pushed our change from our local machines to the remote repository on Github. If we look on Github, we’ll see that the change we made is reflected in the files in our copy of the haiku repository.

      Creating a Pull Request

      We’re now ready to let the maintainers of the project know that we have a change to the repository that we’re confident about and ready to submit. To do this, we’ll click the pull request button to the right.

      Submit a PR

      After the pull request button is clicked, a new page will open with a form that explains what change we made, and shows if the changes made will in any way conflict with the existing content. We’ll add in an appropriate title that details the change, and in the description add an explanation of what changes were made and why. What you add here can vary depending on the project – take a look at the project’s collaboration guidelines to make sure your pull request is formatted correctly.

      After adding in a title and description of the changes made, we’ll scan the pull request page to make sure that our committed change does not conflict with existing changes made to the code repository. If everything checks out, we’ll get a green submit pull request button at the bottom that escalates our request to make a change to the original haiku poem codebase, a contribution that will be live for anyone viewing that main branch. Be patient — it may take maintainers some time to review your request. Amendments and comments can be added on the pull request page, and new commits made to the same affected files will appear in the request’s history.

      Congratulations- we’ve successfully submitted our first pull request!

      In this tutorial, you learned about Git and Github, and successfully identified and submitted a change to a public repository. For Hacktoberfest, you’ll need to submit 4 meaningful pull requests, so again, find the project that resonates with you and have fun hacking!

      To see this tutorial in action, here’s a helpful video that walks you through the process of submitting your first pull request:

      Video: How to Submit Your First PR

      For more information about Hacktoberfest, visit our main page.
      To learn more about Git, visit How to Use Git: A Reference Guide.
      For additional information about Github, visit Github.



      Source link

      Hacktoberfest Workshop Kit: How to Submit Your First Pull Request on Github


      How To Submit Your First Pull Request on GitHub Workshop Kit Materials

      This workshop kit is designed to help an instructor guide an audience without a background in version control or contributing to open source projects through the steps of submitting a pull request from start to finish in roughly thirty minutes. Attendees will finish the workshop with an understanding of version control, open source, Git, and GitHub.

      No prior coding experience is assumed on the part of the audience. Instructors without experience in open source, Git, or GitHub should be able to teach the course after reviewing the material first.

      The aim of this workshop kit is to provide a complete set of resources for a speaker to host a workshop about version control and contributing to open source projects. It includes:

      • Slides and speaker notes that lead participants through setting up their website project, hands-on exercises, and conceptual explanations.
      • A video with a live coding walkthrough of submitting a pull request, tips, and conceptual information about version control and contributing to open source projects.
      • A demonstration repo to allow participants to contribute to an open source project as they follow along in the workshop.

      This workshop kit page is intended to help instructors prepare for the workshop and provide a starting point for learners. Instructors should point learners to this page so they can have access to the slides (which contain useful links).

      If desired, learners can prepare for the workshop by reading the introduction below and making sure that they have the prerequisites ready before the workshop starts.

      If you are interested in participating in this year’s Hacktoberfest, this workshop is a great place to start! This project-based workshop will introduce you to open source, version control, Git, and GitHub using the Cloud Haiku repository as a model. Once you learn the fundamentals, you will know how to contribute to open source projects and submit a pull request on GitHub. No prior coding experience is necessary to follow along in the workshop.

      When software developers work on a project together, oftentimes they’ll need to work on the same code base. While they’re working, each developer needs to know about what changes the others made to the code, so as not to duplicate work or write code over what has already been done. Git, a version control system used to manage developer projects of all sizes, was created in 2005 by Linus Torvalds, the creator of Linux, to help developers contribute to code and share code revisions in a way that was fast, efficient, and inexpensive. Git creates code repositories to help developers edit, share, and publish code for all. GitHub is a cloud-based Git repository hosting service that allows developers to take code that they’ve written on their local machines and share it with the world.

      With Git and GitHub, developers from all over the world collaborate on all sorts of projects — many of the websites you visit regularly are maintained using GitHub. Knowing how to use Git and GitHub, and learning how to contribute to open source projects will provide new developers with a strong start in gaining the skills they need to join the software engineering community at large.

      In this workshop, we’ll introduce you to Git and GitHub, the version control system that Hacktoberfest uses to track your progress, and the repository hosting service that shares projects to collaborate on. By the end of this tutorial, you’ll be ready to submit your first pull request and will be well on your way to participating in Hacktoberfest!

      To participate as a workshop leader or learner, you will need the following:

      • A code editor. In this workshop, we’ll be using Visual Studio Code, which you can download for free for Mac, Windows, or Linux.
      • A web browser. In this workshop, we’ll be using Google Chrome as our default browser, which you can also download for free for Mac, Windows, or Linux.
      • A GitHub account. In this workshop, we’ll make a contribution to an open source repo on GitHub. You can sign up for a free account using your default browser.

      Once you have your prerequisites ready, you will be ready to begin the workshop. Refer to the speaker slides for helpful links after the workshop or watch the How to Submit Your First Pull Request video on the Hacktoberfest resources page to review.



      Source link