Set up the Python Flask framework in 30 minutes and write the first application above, pythonflask

Source: Internet
Author: User

Set up the Python Flask framework in 30 minutes and write the first application above, pythonflask

Flask is a very good Python web framework. It is extremely small and simple. The best thing is that it is easy to learn.
Today I will show you how to build your first Flask web application! Like the official tutorial, you will build your own microblog system: Flaskr. Unlike the official Flask tutorial, we use Stormpath to create and manage user accounts and data, which improves your productivity. The development process will be significantly accelerated!

Let's get started.

Note: This tutorial is intended for new Flask developers to help them understand how to use Flask and Stormpath to build a simple website. This article is a revision of the Flask official tutorial.
Target

The goal of the Flaskr application is simple:

  • Allow users to log on to and log out of this microblog system with a pre-generated account (saved using Stormpath.
  • Allow login users to add entries containing plain text and some HTML body text on the page. Users are considered trustworthy and HTML content will not be reviewed.
  • Display All blog entries on the website homepage in chronological order (new at the top.

The final website should look like this:
Preparation

Before we start, we need to install some Python packages to work! We passed? Python Package Manager pip.
Pip install flask-stormpath

The above command will install two packages: Flask, and Flask-Stormpath, which will be used throughout the tutorial.

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

After you create a Stormpath account and log on to it, you also need to create an API key. You can click the create API Key button on the actions page to complete: https://api.stormpath.com/ui/dashboard

After creating an API key, you will be prompted to download a file named apiKey. properties, which will be used 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 kept properly.

Next, you will want to create a new Stormpath application, please visit the application web page: https://api.stormpath.com/v! Applications ?, Click register application. Create a new application named flaskr with the default options.

Finally, access the account page: https://api.stormpath.com/ui/accounts/create? Create a new user account in flaskr Directory. All accounts created here can be used to log on to the microblog you will set up.
Directory structure

The first thing you need to do is create a directory structure that stores your application code. You need to create several directories and then set your apiKey. properites? Put it in the new project directory:
 

$ mkdir -p flaskr/{static,templates}; cp ~/path/to/apiKey.properties flaskr/$ tree flaskrflaskr├── apiKey.properties├── static└── templates 2 directories, 1 file

The flaskr directory will be the root directory of your application. The static directory is used to store your static files (css, javascript, and image files). The templates directory is used to store your Jinja template (used to render HTML ).
Install an application

Now that your directory structure is ready, we have started to configure the application!

First, create a new file named flaskr. py in your flaskr directory. Put your application code in this file.

Everything starts from here:

 from datetime import datetime from flask import ( Flask, abort, flash, redirect, render_template, request, url_for,)from flask.ext.stormpath import ( StormpathError, StormpathManager, User, login_required, login_user, logout_user, user,) app = Flask(__name__)app.config['DEBUG'] = Trueapp.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()

Notes:

  • You have imported several libraries at the beginning of the flaskr. py file. These libraries will be used in the entire tutorial below.
  • You have created an app object, which is the core of every Flask project.
  • You have added several configuration variables in app. config. App. config is a Python dictionary variable. You can use it to store any custom configurations you want to store. Here we have set several important variables that will be used later:
  • The DEBUG variable can be set to True or False. It is used to control the built-in error reporting behavior of Flask (in development mode, it enables Flask to display detailed error messages)
  • The SECRET_KEY variable is used internally to ensure the security of the Client Session. When deploying a real Flask application, make sure it is a long, random string.
  • STORMPATH_API_KEY_FILE? The variable should point to the location of your apiKey. properties file. For more information, see: http://flask-stormpath.readthedocs.org/en/latest/setup.html
  • The STORMPATH_APPLICATION variable should be the name of the previously created Stormpath application.
  • You have created a stormpath_manager object, which is used to control the Stormpath library. Later, it will help you easily interact with users and user data.
  • You're calling? App. run ()? At the bottom. This tells Flask to run your site in development mode for testing.
  • At last, you called app. run ()?. It tells Flask to run your website in development mode for testing.

After running the following command, you can see that your Flask application is running on port 5000:

$ python flaskr.py * Running on http://127.0.0.1:5000/ * Restarting with reloader

However, when you access http: // 127.0.0.1: 5000, you will see a 404 not found message. This is because you have not defined any view or URL routing.
View

Now you have finished the installation. Let's define the view. The following code should be placed in the flaskr. py file, above which:

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'], reverse=True) return render_template('show_posts.html', posts=posts) @app.route('/add', methods=['POST'])@login_requireddef add_post(): if not user.custom_data.get('posts'):  user.custom_data['posts'] = []  user.custom_data['posts'].append({  'date': datetime.utcnow().isoformat(),  'title': request.form['title'],  'text': request.form['text'], }) user.save()  flash('New post successfully added.') return redirect(url_for('show_posts')) @app.route('/login', methods=['GET', 'POST'])def login(): error = None  if request.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(url_for('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 discuss the above Code.

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

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

Show_posts is just:

  • Iterate all user accounts to find blog 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 each blog post to the posts array.
  • Sort the posts array by date, so the newly released ones are in front.
  • In the form of postsnumbers, an HTML template named show_posts.html is generated.
  • The add_posts view is used to log on to the user to publish a new blog to the website. This view provides the following:
  • The decorator @ app. route ('/add', methods = ['post']) tells Flask that the URL only accepts POST requests. By default, Flask only accepts GET requests.
  • @ Login_required: Make sure that the user has logged in before accessing this view. If you try to POST the view without logging in, you will receive an HTTP 401 unauthorized response.
  • Any decoration? @ Login_required can all access the user variable. This is an object that stores the details of a user account.

Its working mechanism is simple:

  • Check whether there are saved blog posts under the user account. This step is implemented by checking that user. custom_data.get ('posts') is not False. User. custom_data is a Python dictionary in which you can save any user data you want to save.
  • Capture the title and body from the POST request, and create a new post object in the user's posts array.
  • Save the new blog to the Stormpath of the user account.
  • Send a message that will be displayed to the user.
  • Finally, redirect the user to show_posts? View to display the newly added blog.
  • The login and logout views are particularly simple.

The login view simply extracts the email address and password from the user's POST request, captures the user object from the Stormpath, attempts to log on, and creates a local session.

The logout view destroys user sessions.
Template

The following is the template code. Flask uses the Jinja template language, which makes it very easy to compile HTML templates.

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

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

<!doctype html><title>Flaskr</title><link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}"><div> 

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>  <dl>  <dt>Title:  <dd><input type=text size=30 name=title>  <dt>Text:  <dd><textarea name=text rows=5 cols=40></textarea>  <dd><input type=submit value=Share>  </dl> </form> {% endif %} <ul> {% for post in posts %} <li>

Finally, it is the templates/login.html template file:
 

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

What should I pay attention to first? The layout.html template defines a body block, which can be replaced by blocks with the same name in any subtemplate.

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

{% if user.email %}

Because you use Flask-Stormpath, all templates can access a magic user variable. After a user logs in, all the details of the user are visible (so this check can take effect ).

Show_posts.html? The template iterates the posts array, which is passed in when the show_posts view calls render_template. Jinja allows you to use a for loop for anything that can be iterated.

Also, to output the variable content, you need to add curly brackets outside the variable.
 

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

Since we have decided to allow users to input willful HTML code in their blog posts, we have to use the safe filter of the template to output the body block in the blog.

By default, Jinja automatically ignores any special characters, so we need to use the safe filter to display the HTML and Javascript entered by the user.
Add Style

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

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 to provide a decent display style.
Test it

Now we have completed the application code. Let's take a look at the final product!

To run your cool new website, run the following command to restart the Flask web Server:
 

$ python flaskr.py * Running on http://127.0.0.1:5000/ * Restarting with reloader

Then access http: // 127.0.0.1: 5000 in your browser. Now you should be able to see the running flaskr website, and use the Stormpath account to log on and send blog posts.

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.