How to create a simple blog system using the Flask framework

Source: Internet
Author: User
This is the second article in The Flask framework's Learning Guide series. it mainly describes how to create a simple blog system for small projects, if you have any need, you can refer to the previous article about building a flask development environment. Today, we will continue to build a practical project-blog system.

The blog system is very simple. there is only one page, and the Sparrow is small and dirty. The purpose here is not to create a project for the purpose of doing the project. This article aims to convey the following knowledge points through this exercise:

1. understand the directory structure of the flask project globally

2. operating mechanism of the flask project

3. implement the MVC architecture using the flask framework

4. flask-sqlalchemy

1. create a project: blog system

In pycharm, create a flask project, for example:

The directory structure is as follows: very simple, a static folder, a templates folder, and a py file

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

2. directory structure reconstruction and Package management

For the above structure, under the blog3 directory at the top,

1. create a new runserver. py file as the unified project portal file.

2. create a new blog folder, move the existing static, templates, and blog3.py files to the blog folder, and create the controller and model folders respectively. Change blog3.py To _ init _. py,

The current directory is as follows:

This is equivalent to a large project structure:

1) the blog2 directory at the top is the project name. a project can contain multiple modules, that is, applications. Each application has its own configuration file, initialization file, and MVC architecture.

2) runserver. py: same as the application module, used as the project startup file

3) Level 2 blog2 Directory: Module Name

Controller Directory: C in MVC, mainly storing view functions

Model Directory: M in MVC, which mainly stores object files and maps tables in the database.

Templates: V in MVC, which stores html files

Static: static files, mainly used to store files such as css and js.

_ Init _. py: module initialization file,FlaskThe program object must be created in_ Init _. pyFile, then we can safely import and reference each package.

Setting. py: configuration file, database username and password, etc.

3. develop code

1. run the project first:

1) write the _ init _. py file to create a project object. the code is as follows:

#-*-Coding: UTF-8-*-from flask import Flask # Create a 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:

Enter http: // 127.0.0.1: 5000/in the browser to display helloworld.

Now, the prototype of the project can run normally, and the following things are simple. add the content so that the project can be bloody.

2. design a database

This exercise is relatively simple. There are two tables, one user table and one article table. We use the python orm framework flask-sqlalchemy to create, add, delete, modify, and query tables.

Add the User. py and Category. py files to the model folder. the content is 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(10),unique=True)  password = db.Column(db.String(16))  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(20),unique=True)  content = db.Column(db.String(100))  def __init__(self,title,content):    self.title = title    self.content = content  def __repr__(self):    return '
 
  ' % self.title
 

3) create the setting. py file under the module directory blog2 and configure the database connection information.

# _ * _ Coding: UTF-8 _ * _ # DEBUG mode: DEBUG = TrueSQLALCHEMY_TRACK_MODIFICATIONS = False # keySECRET_KEY = 'a0zr98j/3yX R ~ XHH! JmN] LWX /,? RT '# mysql database connection information. here, change it to your account SQLALCHEMY_DATABASE_URI = "mysql: // username: password @ ip: port/dbname"

4) read the configuration file from the project

Modify _ init _. py: add the following content (in red ):

#-*-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') # load the configuration file content app. config. from_object ('blog2. setting ') # The setting file name in the module. you do not need to add the py suffix app. config. from_envvar ('flaskr _ setting') # environment variable, pointing to the path of the configuration file setting # create database object db = SQLAlchemy (app)

Note: the environment variables of FLASKR_SETTINGS must be manually set. in the window, enter:

E:\workdir\blog2> set FLASKR_SETTINGS=E:\workdir\blog2\blog2\setting.py

Or click my computer> Advanced> environment variable to create a new one.

5) create databases and tables

In windows command line mode, run cd to the project runserver. py directory and enter python shell:

Enter the red part:

E:\workdir\blog2>pythonPython 2.7.10 (default, May 23 2015, 09:44:00) [MSC v.1500 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> from blog2 import db>>> db.create_all()>>>>>>

If no error is returned, the database and table are created successfully. In this case, go to the database to view:

The database already exists. check the table again. The corresponding B _user and B _category tables are not found. Why? Are the two classes in the "model" directory not found. The problem is that the model package is not introduced in the __init _. py file, and the _ init _. py object class cannot be found. Remember: All module objects are created in _ init _. py.

Add the following code to _ init _. py in the blog2 Directory:

# The statement must be declared after the app object and used to import the model. Otherwise, the table from blog2.model import User and Category cannot be created.

Run the preceding command again: db. create_all. The table is successfully created.

3. add an interface template. for example, the logon page displays the blog article page and the add blog page.

Add three html files under the templates Directory:

Layout.html:

  Flaskr 
  

Flaskr

{% if not session.logged_in %} log in {% else %} log out {% endif %}

{% for message in get_flashed_messages() %}

{{ message }}

{% endfor %} {% block body %}{% endblock %}

Login.html:

{% extends "layout.html" %}{% block body %} 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 here so far {% endfor %}
{% endblock %}

Add the css file style.css to the static file.

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 blog_message.py file in the controller Directory:

from blog2.model.User import Userfrom blog2.model.Category import Categoryimport osfrom blog2 import app,dbfrom flask 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 = 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 _ init _. py file in the module-level Directory (blog2 directory) to the View module. the code is as follows:

# It is declared only after the app object and is used to import the view module from blog2.controller import blog_manage

5. run the project with the following effects:

1) input http: // 127.0.0.1: 5000/. normally, you should be blank because there is no data.

2) click log in.

I forgot to tell you that you need to add a user to the B _user table in advance, because login needs to verify the user, otherwise you will not be able to log on successfully.

3) add entries

The above is all the pages of this small project. it's easy. You can do it !!!

[Conclusion]: through this exercise, do you have a certain understanding of the flask framework running mechanism? do you already have a global understanding? if OK, then this small exercise has value.

References:

[Flask quick start Chinese edition] http://docs.jinkan.org/docs/flask/

Flask quick start English edition http://flask.pocoo.org/docs/0.11/

Flask-sqlalchemy Chinese edition 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.