A simple blog system and a Flask Learning Guide for the flask framework

Source: Internet
Author: User

A simple blog system and a Flask Learning Guide for the flask framework

I wrote an article about building a flask development environment. Today, I will continue with a practical small 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 '<User %r>' % 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 '<Category %r>' % 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:

 <!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 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/

Related Article

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.