Flask framework of learning Guide to the production of simple blog system _python

Source: Internet
Author: User
Tags create database

Before writing a flask development environment to build, continue today, to carry out a small project-blog system.

Blog system is very simple, only one page, and then though small spite. The goal here is not to do projects, this article is meant to convey the following knowledge through this exercise:

1, the overall understanding of the Flask project directory structure

2. Operation mechanism of FLASK Project

3, flask framework to implement MVC architecture

4, flask-sqlalchemy operation MySQL Database

One, new project: Blog system

In Pycharm, create a new flask project, as shown in the following figure:

The finished directory structure is this: very simple, a static folder, a Templates folder, a py file

The above directory structure is flask Initial structure, this can only deal with very small projects, for large and complex projects, we need to introduce package management, MVC architecture design.

Second, the directory structure reconfiguration, introduces the package management

For the above structure, at the top of the Blog3 directory,

1, a new runserver.py file, as a project unified entry file

2, the new Blog folder, the existing static,templates,blog3.py moved to the blog folder, and then built controller, model folder. Change the name of blog3.py to __init__.py,

The directory now looks like this:

This is the equivalent of a large engineering structure:

1 The top-level BLOG2 directory is the project name, a project can include multiple modules, that is, application, each application has its own configuration files, initialization files, MVC architecture.

2) runserver.py: With the application module peer, as the project startup file

3 Second Level BLOG2 directory: module name

Controller directory: C in MVC, main store view functions

Model directory: M in MVC, the main storage entity class files, mapping database tables

V in Templates:mvc, storing HTML files

Statics: Static files, mainly storing Css,js and other documents

__init__.py: module initialization file,flask Program object creation must be done in __init__.py file, then we can safely import reference each package.

setting.py: Configuration file, database username password, etc.

Third, the development of code

1. Run the project first:

1 Write __init__.py file, create project object, code as follows:

#-*-Coding:utf-8-*-from
flask import flask

#创建项目对象
app = Flask (__name__)

2 Add the following code in the runserver.py file:

From Blog3 Import app

@app. Route ('/")
def Hello_world (): Return
  ' Hello world! '
if __name__ = = ' __main__ ':
  app.run (debug=true)

3) Run runserver.py file:

Then enter in the browser: Http://127.0.0.1:5000/, will display HelloWorld words

Here, the prototype of the project can be normal operation, the following things are simple, add content, let the project Flesh and Blood bar.

2. Design Database

This exercise is simpler, on two tables, a user table, an article table. We use Python's ORM framework Flask-sqlalchemy to implement table creation, and to increase the search function.

Add user.py and category.py files to the Model folder as follows:

1) user.py:

From BLOG2 Import DB

class User (db. Model):
  __tablename__ = ' b_user '
  id = db. Column (db. Integer,primary_key=true)
  username = db. Column (db. String (a), unique=true)
  password = db. Column (db. String ()

  def __init__ (self,username,password):
    self.username = username
    self.password = password
  def __repr__ (self): return
    ' <user%r> '% self.username

2) category.py

From BLOG2 Import DB

class Category (db. Model):
  __tablename__ = ' b_category '
  id = db. Column (db. integer,primary_key=true)
  title = db. Column (db. String (unique=true)
  content = db. Column (db. String (M)

  def __init__ (self,title,content):
    self.title = title
    self.content = Content
  def __ Repr__ (self): return
    ' <category%r> '% self.title

3 in the module directory blog2 new setting.py file, configuration database connection information

# _*_ Coding:utf-8 _*_

#调试模式是否开启
DEBUG = True

sqlalchemy_track_modifications = False
#session必须要设置key
secret_key= ' A0zr98j/3yx r~xhh!jmn] lwx/, huh? RT '

#mysql数据库连接信息, here changed to own account
Sqlalchemy_database_uri = "Mysql://username:password@ip:port/dbname"

4 Let the project read the configuration file

Modify __init__.py: Add the following (Red section):

#-*-Coding:utf-8-*-from
flask import flask to
flask_sqlalchemy import sqlalchemy
app = Flask (__name_ _) #import os#print Os.environ.keys () #print os.environ.get (' flaskr_settings ') #加载配置文件内容app. Config.from_object (' Blog2.setting ')   #模块下的setting文件名, without adding a py suffix app.config.from_envvar (' flaskr_settings ')  #环境变量, Path to configuration file setting # CREATE database Object db = SQLAlchemy (APP)

Note: The flaskr_settings environment variable needs to be individually set by hand, and can be entered at the command line under window:

E:\workdir\blog2> Set flaskr_settings=e:\workdir\blog2\blog2\setting.py

Or click on my Computer--> advanced--> environment variable, create a new one.

5 Create databases and tables

Under Windows command-line mode, the CD to the project runserver.py under that directory, into the Python shell:

Enter the Red section:

E:\workdir\blog2>python
python 2.7.10 (default, May 2015, 09:44:00) [MSC v.1500-bit (AMD64)] on WI
n32
   type "Help", "copyright", "credits" or "license" for the more information.
>>> from BLOG2 Import db
>>> Db.create_all ()
>>>
>>>

If no error output represents the creation of the database and the table succeeded. Then we go to the database to view:

The database already exists, then look at the table situation: found no corresponding b_user and b_category table. What is this for? Did not find two classes under the Model directory. The problem is that the __init__.py file did not introduce the model package, causing __init__.py to not find entity classes. Remember: All module object creation is done in __init__.py

Add the following code to the __init__.py in the BLOG2 directory:

#只有在app对象之后声明, for import model otherwise the table from
Blog2.model import user,category cannot be created

Run the above command again: Db.create_all () method. The table has been created successfully.

3, add interface template: such as landing page, display blog article page, add blog page

Add three HTML files to the templates directory:

Layout.html:

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

Login.html:

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

Show_entries.html:

{% extends ' layout.html '%}
{% block body%}
 {% if session.logged_in%}
  <form action= ' {url_for (' Add_entry '}} ' method= ' POST ' class=add-entry>
   <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 class=entries>
 {% for entry in entries%}
  <li> 
 

Add CSS file to corresponding static: Style.css

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;}

4. Add business logic

Create a new blog_message.py file in the Controller directory:

From Blog2.model.User import User blog2.model.Category import Category import os from blog2 import app,db from Flas
K Import Request,render_template,flash,abort,url_for,redirect,session,flask,g @app. Route ('/') def show_entries (): Categorys = Category.query.all () return render_template (' show_entries.html ', Entries=categorys) @app. Route ('/add ', methods=[' POST '] def add_entry (): If not session.get (' logged_in '): Abort (401) title = request.form[' title '] content = req uest.form[' text '] category = Category (Title,content) db.session.add (category) Db.session.commit () Flash (' New entry was Successfully posted ') return Redirect (Url_for (' show_entries ')) @app. Route ('/login ', methods=[' get ', ' POST ']) def login  (): Error = None if Request.method = ' POST ': username = request.form[' username '] Password = request.form[' password '] User = User.query.filter_by (username=request.form[' username ').-A () passwd = User.query.filter_by (password= request.form[' password ']). The IF user is None:error = ' inValid username ' elif passwd are none:error = ' Invalid password ' else:session[' logged_in '] = True Flash (' You were logged I
N ') return to redirect (Url_for (' show_entries ')) return render_template (' login.html ', Error=error) @app. Route ('/logout ') def logout (): Session.pop (' logged_in ', None) Flash (' Your were logged out ') return redirect (Url_for (' show_entries '))

Never forget to introduce the view module to the __init__.py file in the module-level directory (BLOG2 directory), as follows:

#只有在app对象之后声明, to import the View module from
blog2.controller import blog_manage

5, the operation of the project, the results are as follows:

1 input http://127.0.0.1:5000/, under normal circumstances you should be blank, because there is no data.

2) Click Log In

Forget to tell you, you have to first in the B_user table to add a user oh, because the login to verify the user, otherwise you are unable to login successfully.

3) Add entries

The above is all the pages of this small project, very simple. You'll be able to handle!!!.

"Summary": Through this exercise, whether the flask framework operating mechanism to understand, is not already have a global understanding, if OK, then this small exercise has the value of existence.

Reference documents:

"Flask Fast starter Chinese Version" http://docs.jinkan.org/docs/flask/

"Flask Quick Start English" http://flask.pocoo.org/docs/0.11/

"Flask-sqlalchemy Chinese Version" http://www.pythondoc.com/flask-sqlalchemy/index.html

"Flask-sqlalchemy English Edition" http://flask-sqlalchemy.pocoo.org/2.1/

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.