A simple blog system for making a learning guide to the FLASK framework

Source: Internet
Author: User
Previously wrote an article Flask development environment build, continue today, carry on a small project-blog system of actual combat.

Blog system is very simple, only one page, and then small perfectly formed. The goal here is not to do projects for the project, this article is intended to convey the following several points of knowledge through this exercise:

1. Understand the directory structure of the Flask project from a global view

2. Operation mechanism of FLASK Project

3. Flask Framework to implement MVC architecture

4. Flask-sqlalchemy Operation MySQL Database

First, the New Project: Blog system

In Pycharm, create a new flask project, such as:

After the completion of the 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.

II. directory structure reconstruction, introduction of package management

For the above structure, in the top Blog3 directory,

1, create a new runserver.py file, as a Project unified import file

2, the new Blog folder, the existing static,templates,blog3.py moved to the blog folder, and then the controller, model folder respectively. Renamed blog3.py to __init__.py,

Now the directory looks like this:

This is the equivalent of a large engineering structure:

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

2) runserver.py: Same as application module, as Project startup file

3) Second Level BLOG2 directory: module name

Controller directory: C in MVC, mainly storing view functions

Model directory: M in MVC, primarily storing entity class files, mapping tables in the database

V in Templates:mvc, storing HTML files

Static files, mainly storing Css,js and other files

__init__.py: The module initialization file, the creation of theFlask program object must be done in the __init__.py file, and then we can safely import the reference to each package.

setting.py: Configuration file, database user name password, etc.

Third, the development of code

1. Run the project first:

1) write the __init__.py file and create the project object with the following code:

#-*-Coding:utf-8-*-from flask Import flask# Create project Object app = Flask (__name__)

2) Add the following code to 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 the runserver.py file:

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

Here, the project prototype can run normally, the following things are simple, add content, let the project Flesh and Blood bar.

2. Design Database

This exercise is relatively simple, with two tables, a user table, and an article table. We use the Python ORM framework Flask-sqlalchemy to realize the creation of table, the function of adding and checking.

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

1) user.py:

From blog2 import Dbclass User (db. Model):  __tablename__ = ' b_user '  id = db. Column (db. Integer,primary_key=true)  username = db. Column (db. String (Ten), unique=true)  password = db. Column (db. String (+))  def __init__ (self,username,password):    self.username = username    self.password = password  def __repr__ (self):    return '
 
  
   
  % self.username
 
  

2) category.py

From blog2 import Dbclass Category (db. Model):  __tablename__ = ' b_category '  id = db. Column (db. integer,primary_key=true)  title = db. Column (db. String (a), unique=true)  content = db. Column (db. String (+))  def __init__ (self,title,content):    self.title = title    self.content = Content  def __ Repr__ (self):    return '
 
  
   
  % self.title
 
  

3) Create a new setting.py file under Module directory BLOG2, configure database connection information

# _*_ coding:utf-8 _*_# debug mode Open debug = Truesqlalchemy_track_modifications = False#session must be set keysecret_key= ' A0Zr98j/ 3yX r~xhh!jmn]lwx/,? RT ' #mysql数据库连接信息, change to your account here 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 flaskfrom flask_sqlalchemy Import Sqlalchemyapp = Flask (__name__) #import os#print Os.environ.keys () #print os.environ.get (' flaskr_settings ') #加载配置文件内容app. Config.from_object (' blog2.setting ')   # The setting file name under the module, without the py suffix app.config.from_envvar (' flaskr_settings ')  #环境变量, point to the path to the configuration file setting # CREATE database Object db = SQLAlchemy (APP)

Note: The flaskr_settings environment variable needs to be set manually and can be entered at the command line under window:

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

Or click My Computer--advanced--environment variables, create a new one.

5) Creating databases and tables

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

Enter the Red section:

E:\workdir\blog2>pythonpython 2.7.10 (default, May, 09:44:00) [MSC v.1500-bit (AMD64)] on Win32type "Help", "Copyright", "credits" or "license" for more information.>>> from blog2 import db>>> db.create_all () ;>>>>>

If there is no error, the output represents the creation of the database and the table succeeded. Then we go to the database to see:

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

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

#只有在app对象之后声明, to import the model otherwise you cannot create a table from Blog2.model import user,category

Run the above command again: the 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 under the templates directory:

Layout.html:

  Flaskr 
 
     

Flaskr

{% if not session.logged_in%} Log in {% of else%} log out {% endif%} {% of message in get_flashed_messages ()%} {{message}}} {% ENDFOR%}

Login.html:

Login

{% if error%}

Error: {{Error}} {% ENDIF%} {% Endblock%}

Show_entries.html:

{% extends "layout.html"%} {% block body%} {% if session.logged_in%}   {% ENDIF%} 
 
  
  
    {% for entry in entries%}
  • {{Entry.title}}

    {{Entry.content|safe}} {% Else%}
  • Unbelievable. No entries this far
{% Endblock%}

Add a CSS file to the 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 under the Controller directory:

From Blog2.model.User import userfrom blog2.model.Category import categoryimport osfrom blog2 import app,dbfrom flask impo RT 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 = request.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 = noneif Request.method = = ' POST ': username = request.form[' username ']password = request.form[' password '] user = User.query.filter_by (username=request.form[' username '). First () passwd = User.query.filter_by (password= request.form[' password '). First () if user is None:error = ' Invalid username ' elif passwd is None:Error = ' Invalid password ' else:session[' logged_in '] = Trueflash (' You were logged in ') return redirect (Url_for (' Show_ Entries ') return render_template (' login.html ', Error=error) @app. Route ('/logout ') def logout (): Session.pop (' Logged_ In ', None] Flash (' You were logged out ') return redirect (Url_for (' show_entries '))

Do not forget to introduce the view module in the __init__.py file of the module-level directory (BLOG2 directory), the code is as follows:

#只有在app对象之后声明 for importing the View module from Blog2.controller import blog_manage

5, the operation of the project, the effect is as follows:

1) Enter http://127.0.0.1:5000/, under normal circumstances your should be blank, because there is no data.

2) Click Log In

Forgot to tell you, you have to add a user in the B_user table in advance, because login to verify the user, otherwise you will not be able to log on successfully.

3) Add entry

These are all the pages of this small project, very simple. You will be able to handle it!!!

"Summary": Through this exercise, whether the flask framework operating mechanism have some understanding, is not already have a global understanding, if OK, then this little exercise there is value.

Reference documents:

"Flask Quick Start Chinese version" http://docs.jinkan.org/docs/flask/

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

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

"Flask-sqlalchemy English Version" 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.