30 minutes to build Python's flask framework and write the first application _python

Source: Internet
Author: User
Tags version control system

Flask is a great Python web framework. It's very small, simple, and the best thing is that it's easy to learn.
Today I'll take you to build your first flask Web App! As with the official tutorials, you will build your own microblogging system: Flaskr. Unlike the official flask tutorials--we use Stormpath to create and manage user accounts and data--you work more efficiently. The development process will accelerate dramatically!

Let's get this started.

Note: This tutorial is intended for flask developers to help them understand how to build a simple web site using flask and Stormpath. This is the revision of the official Flask tutorial.

The goal of FLASKR application is simple:

    • Allows users to log in with a previously generated account (saved using Stormpath), and login to this micro-blogging system.
    • Allow login users to add entries in the page that contain plain text and some HTML body text. The user is considered trustworthy and the HTML content is not censored.
    • Displays all blog entries in chronological order (new on top) at the homepage of the website.

The final website should look like this:
Ready to

Before we start, we need to install some Python packs to work! We're through? Python Package Manager pip to complete the event.
Pip Install flask Flask-stormpath

The above command installs two packages: flask, and Flask-stormpath, both of which will be used throughout the tutorial.

Next, you need to create a Stormpath account. You can register at the Stormpath website: https://api.stormpath.com/register

When you create a Stormpath account and log in, you also need to create an API key. You can do this by clicking the Create API Key button on the action page: Https://api.stormpath.com/ui/dashboard

After creating the API key, you will be prompted to download a file called Apikey.properties, which we will use later.

Note: Do not check the Apikey.properties file into your version control system (if you are using it)! This file stores your Stormpath certificate and should be properly kept.

Next, you will want to create a new Stormpath application, please visit the application page: Https://api.stormpath.com/v#!applications?, click Register Application. Create a new application named Flaskr, with the option to default.

Finally, visit the Account page: Https://api.stormpath.com/ui/accounts/create? , create a new user account in Flaskr directory. All the accounts created here can be used to log into the micro blog you will build.
directory Structure

The first thing you need to do is create a directory structure that holds your application code. You need to create several catalogs and then put your apikey.properites in the new project directory:

$ mkdir-p Flaskr/{static,templates}; CP ~/path/to/apikey.properties flaskr/
$ tree flaskr
└── Templates
2 directories, 1 file

The Flaskr directory will be the root directory you apply. The static directory is used to store your static files (css,javascript, and image files). The templates directory is used to store your Jinja templates (for rendering HTML).
Installation Application

Now that your directory structure is set up, we start to configure the application!

First, create a new file named flaskr.py in your Flaskr directory. Your application code is placed in this file.

Everything will start here:

From datetime import datetime from
flask import (
 Render_ Template,
) from
flask.ext.stormpath import (
App = Flask (__name__)
app.config[' DEBUG ' = True
app.config[' secret_key '] = ' some_really_long_random_ String_here '
app.config[' stormpath_api_key_file '] = ' apikey.properties '
app.config[' stormpath_ Application '] = ' flaskr '
Stormpath_manager = Stormpathmanager (APP)
if __name__ = ' __main__ ':
 app.run ( )

To be concerned with:

  • At the beginning of the flaskr.py file you have imported several libraries--the entire tutorial will use them
  • You created an App object--it's the core of every flask project.
  • You have added several configuration variables to the app.config. App.config is a python dictionary variable that you can use to store any custom configurations you want to store. Here we set a number of important variables to use later:
  • The DEBUG variable can be set to TRUE or false. It is used to control flask's built-in error reporting behavior (it allows flask to display detailed error messages in development mode)
  • Secret_key variables are used internally to guarantee the client's session security. When deploying a real flask application, make sure that it is a long, randomly generated string.
  • Stormpath_api_key_file? The variable should point to your apikey.properties file location. For more information see: http://flask-stormpath.readthedocs.org/en/latest/setup.html
  • The stormpath_application variable should be the name of the Stormpath application you created earlier.
  • You create a Stormpath_manager object that controls the Stormpath library, which will help you easily interact with users and user data.
  • ' Re Calling?app.run () at the bottom. This is tells Flask to run your site in development mode for testing.
  • In the end you call the App.run ()? It tells Flask to run your site in development mode for easy testing.

After you run the following command, you can see that your flask application starts running on port 5000:

$ python flaskr.py
 * Running on
 * Restarting with Reloader

However, when you visit, you will see a 404 Not Found information. This is because you have not yet defined any views or URL routes.

Now that you have finished installing the parts, we will define the view. The following code should be placed in the flaskr.py file, above this:

if __name__ = = ' __main__ ':
 app.run ()

The code is as follows:

@app. Route ('/') def show_posts (): posts = [] for account in Stormpath_manager.application.accounts:if Account.custom _data.get (' posts '): Posts.extend (account.custom_data[' posts ']) posts = sorted (posts, Key=lambda k:k[' Date '), revers
E=true) return render_template (' show_posts.html ', posts=posts) @app. Route ('/add ', methods=[' POST ') @login_required Def add_post (): If not user.custom_data.get (' posts '): user.custom_data[' posts '] = [] user.custom_data[' posts '].appen D ({' Date ': Datetime.utcnow (). Isoformat (), ' title ': request.form[' title '], ' text ': request.form[' text '],}) USER.S
 Ave () Flash (' New post successfully added. ') Return Redirect (Url_for (' show_posts ')) @app. Route ('/login ', methods=[' get ', ' POST ']) def login (): Error = None if re
   Quest.method = = ' POST ': try: _user = user.from_login (request.form[' email '), request.form[' password '] Login_user (_user, remember=true) Flash (' You were logged in. ") return redirect (" Show_posts ')) except Stormpatherror, Err:error = err.message return render_template (' login.html ', error=error) @app
 . Route ('/logout ') def logout (): Logout_user () Flash (' You were logged out. ')

 Return Redirect (Url_for (' show_posts '))

Let's talk about the code above.

You may notice that the function defined first is show_posts. This function is used to display posts posted on the front page of the site. As you may have guessed, the adorner @app.route ('/') tells Flask how to run this function.

Each time the user requests the URL "/", flask runs the show_posts and returns the output to the user.

Show_posts is just:

    • Iterate through all the user accounts and find posts. Each blog post is a simple Python dictionary in the following format:
 ' date ': ' 2014-04-01t22:50:49.762475 ', '
 text ': ' Blog content. ',
 ' title ': ' Post title '
    • Add to the posts array every blog post you find.
    • Sorts the posts array by date, so the new publication is in the front.
    • The posts array is used as input to render an HTML template called show_posts.html.
    • The add_posts view is used to log in users to publish New Boven to the Web site. This view brings you to the following things:
    • The adorner @app.route ('/add ', methods=[' POST ') tells Flask that the URL accepts only POST requests. Flask accepts only get requests by default.
    • The @login_required adorner ensures that the user has logged in before the view can be accessed. If the user fails to log in and tries to post the view, an HTTP 401 unauthorized response is obtained.
    • Any decorations? A @login_required view can access the user variable. This is an object that holds the details of the user account.

Its working mechanism is simple:

    • Check to see if there are any saved posts under the user account. This step is achieved by checking that user.custom_data.get (' posts ') is not false. User.custom_data is a python dictionary where you can save any user data that you want to save.
    • Grab the title and body from the POST request and create a new post object in the user's posts array.
    • Save New Boven to the Stormpath of the user account.
    • Issue a message that will be displayed to the user later.
    • Finally, redirect the user to the Show_posts view so that the newly added blog post can be displayed.
    • The login and logout views are particularly simple.

The login view simply extracts the e-mail address and password from the user post request, then crawls the user object from the Stormpath, attempts to log on, and creates a local session.

The logout view is the destruction of a user session.

The next thing to add is the template code. Flask uses the Jinja template language, which makes it very easy to write HTML templates.

Let's define a layout template templates/layout.html as the start. The other templates we write later will come from this base template. This strategy is useful because it allows you to define the template code that will be referenced multiple times in one place.

Add the following code to your layout.html template file:

<!doctype html>
<link rel=stylesheet type=text/css href= "{{Url_ For (' Static ', Filename= ' Style.css '}} ' >

Next is the templates/show_posts.html template file:

{% extends ' layout.html '%}
{% block body%}
 {% if User.email%}
 <form action= "{{url_for (' Add_post ')}}" method=post>
  <dd>< Input Type=text size=30 name=title>
  <dd><textarea name=text rows=5 </textarea>
  <dd><input type=submit value=share>
 { % endif%}
 {% for post in posts%}

Finally, the templates/login.html template file:

{% extends ' layout.html '%}
{% block body%}

The first thing to note is that? The layout.html template defines a body block that can be replaced by a block of the same name in any child template.

The layout.html template displays a login or logout template and also displays all flashback information.

{% if User.email%}

Because you're using Flask-stormpath, all templates have access to a magical user variable. When a user is logged in, all the details of the user are visible (so this check takes effect).

Show_posts.html? template iteration posts array, which is passed in when called render_template by the show_posts view. Jinja allows you to use for loops for anything that can be iterated.

It's also important that you add curly braces to the variables to output the variable content.

{{post[' text ']|safe}}

Now that we have decided to allow users to input wayward HTML code into their posting, we have to use the safe filter of the template to output the body block in the blog.

Jinja automatically ignores any special characters by default, so we have to use the safe filter to display the HTML and JavaScript that the user has entered.
Add Style

The last thing to do is to create a static/style.css file with the following contents:

Body   {font-family:sans-serif; background: #eee;}
A, H1, H2  {color: #377ba8;}
H1, H2   {font-family: ' Georgia ', serif; margin:0;}
H1    {border-bottom:2px solid #eee;}
H2    {font-size:1.2em}
. Page   {margin:2em auto; width:35em; border:5px solid #ccc;
     Padding:0.8em; Background:white; }
. entries  {list-style:none; margin:0; padding:0;}
. Entries Li  {margin:0.8em 1.2em;}
. Entries Li H2 {margin-left: -1em}
. Add-entry  {font-size:0.9em; border-bottom:1px solid #ccc;}
. Add-entry DL {Font-weight:bold}
. Metanav  {text-align:right; font-size:0.8em; padding:0.3em;
     Margin-bottom:1em; Background: #fafafa; }
. Flash   {background: #cee5F5; padding:0.5em;
     border:1px solid #aacbe2; }
. Error   {background: #f0d6d6; padding:0.5em;}

This file will be loaded by the layout.html template, providing a decent display style.
Test It

Now that we have completed the application code, let's look at the final product!

To run your cool new site, you have to start by restarting the Flask Web server with the following command:

$ python flaskr.py
 * Running on
 * Restarting with Reloader

Then visit in your browser. You should now be able to see the running Flaskr Web site and be able to log in with the Stormpath account, post posts, and so on.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.