preface

Flask is a lightweight Web framework written in Python that is much more flexible and lightweight than other frameworks of the same type. It’s also very customizable, users can add features according to their own needs, and has a great library of plug-ins, which is why the framework has been so popular in python. This article we will use this framework to write a blog site of their own! And teach you how to use Intranet penetration tools to process projects, so that local projects can be accessed on the public network!

Let’s start with some demos of the blog Web project we developed.

The project mainly includes the following functions: personal registration and login module, home page article display module, article publishing module introducing MD format, account cancellation module, article classification and editing module, article publishing and modification module and article display paging module, database management module.

Below we write the code of each module

1. Personal registration and login module

The main purpose of this module is to let the user register the user, and then judge whether the password entered is consistent, and write the result to the database.

from flask import render_template, redirect, url_for, request, flash, session
from front_back import front
from modles.dbmodels import User, db
import hashlib
from utils import login_check

@front.route('/login',methods=['GET'.'POST'])
def login(a):
    if request.method= ='GET':
        return render_template('login.html')
    elif request.method=='POST':
        username=request.form.get('username')
        password=request.form.get('password')
        user=User.query.filter_by(username=username,password=password).first()
        print(user)
        if user:
            session['user'] =username
            print(session['user'])
            flash('Login successful')
            return redirect(url_for('front.index'))
        else:
            flash('Login failed')
            return redirect(url_for('front.login'))
​
@front.route('/register',methods=['GET'.'POST'])
def register(a)A get request returns the page, a POST request receives the form dataif request.method = ='GET':
            return render_template("register.html")
        elif request.method == 'POST':
            username = request.form.get('username')
            password = request.form.get('password')
            check_password = request.form.get('check_password')
​
            if username and password and password == check_password:
                md5 = hashlib.md5()
                md5.update(password.encode('utf-8'User = user () user.username = user () user.username = user () user.username = user () user.password=password
                print(username,password)
            try:
               db.session.add(user)
               db.session.commit(a)
               flash('Registered successfully, welcome to visit my personal blog! ')
               return redirect(url_for('front.register'))
            except Exception:
               flash('Registration failed, please check your password and re-register')
               return redirect(url_for('front.register'))
        else:
             flash('Registration failed')
             return redirect(url_for('front.register'))
Copy the code

2. Home page article display module

This module integrates the pagination function. When the number of published articles cannot be fully displayed on the current page, it uses the added pagination method to display them. Bootstrap provides the pagination navigation bar to write.

@front.route('/index')
@front.route('/')
# @login_requireddef index() :
    page=int(request.args.get('page',default=1))   # find incoming? Page =? The argument, if not, defaults to 1, because you're returning a string, so you need to convert it to an int
    #pre_page=? This sets the maximum number of entries per page
    paginate=Article.query.order_by(Article.create_time.desc()).paginate(page=page,per_page=5)
    article=paginate.items
    groups=ArticleGroup.query.all(a)Get all the data for the model
    return render_template("index.html",groups=groups,article=article,paginate=paginate)
Copy the code

3. Article details display module

This module is mainly to get all the time of the article model and display it, and make accurate display through the ID of the article

@front.route('/article_detail/<int:article_id>') # @login_required def article_detail(article_id): Article = article.query.get (article_id) groups= articlegroup.query.all () # return render_template("article_detail.html",groups=groups,article=article)Copy the code

4. Article publishing module

This module introduces an article writing module in MD format. Users can write and publish articles according to the syntax of MD. At the same time, a grammar preview box on the right is added to facilitate users to see the presentation of articles

@front.route('/add_article',methods=['GET','POST']) # @login_required def add_article(): if request.method=='GET': Return render_template("add_article.html",groups=groups) elif request.method=='POST': title=request.form.get('title') content=request.form.get('content') gid=request.form.get('gid') User.query.filter_by(username=session.get('user')).first() uid=user.id Create_time =datetime.datetime.now() article= article () article.title=title article.content=content article.gid=gid article.uid=uid article.create_time=create_time print(user,title,content,gid,uid,create_time) try: Db.session.add (article) db.session.com MIT () flash(' add %s succeeded '% title) Return redirect(url_for('front.add_article')) except Exception: Flash (' failed to add %s' % title) return redirect(url_for('front.add_article'))Copy the code

5. Add classification module to the article

In this module, users can input the name of the group to be added, and then select the color of the group to be displayed, and store the relevant data in the database

@front.route("/add_group",methods=['GET','POST']) def add_group(): if request.method=='GET': groups = ArticleGroup.query.all() colors=['default','primary','success','into','warning','danger'] return render_template('add_group.html',colors=colors,groups=groups) elif request.method=='POST': name=request.form.get('name') color=request.form.get('color') group=ArticleGroup() group.name=name group.color=color try: Db.session.add (group) db.session.com MIT () flash(" Group added successfully ") return redirect(url_for('front. Manage ')) except Exception: Flash (" add failed ") return redirect(url_for('front.manage'))Copy the code

6. Article classification management module

This module is mainly on the user edit groups and color edit and delete the management function

@front.route("/article_group_manage") def article_group_manage(): groups = ArticleGroup.query.all() return render_template('article_group_mange.html',groups=groups) @front.route('/edit_group/<int:gid>',methods=['GET','POST']) def edit_group(gid): if request.method=='GET': Group = articlegroup.query.get (gid) colors = ['default', 'primary', 'success', 'into', 'warning', 'danger'] return render_template('edit_group.html',group=group,colors=colors,groups=groups) elif request.method=='POST':  name=request.form.get("name") color=request.form.get("color") group=ArticleGroup.query.get(gid) group.name=name group.color=color try: Db.session.add (group) db.session.com MIT () flash(" modified successfully ") return redirect(url_for("front.article_group_manage")) except Exception: Flash (" modify failed ") return redirect(url_for("front.article_group_mange") # delete view function @front.route('/delete_group/<int:gid>') def delete_group(gid): group=ArticleGroup.query.get(gid) try: Db.session.delete (group) db.session.com MIT () flash(' delete %s succeeded '% group.name) return redirect(url_for("front.article_group_manage")) except Exception: Flash (' delete %s failed '% group.name) return redirect(url_for("front.article_group_manage"))Copy the code

7. Article management module

This module provides the article management function, if the user has published the article to continue to improve the idea can be edited in this module, and the article to delete or edit re-published operation.

Copy the code
@front.route('/edit_article/<int:article_id>',methods=['GET','POST']) def edit_article(article_id): if request.method=='GET': Article = article.query.get (article_id) groups= articlegroup.query.all () return render_template('edit_article.html',groups=groups,article=article) elif request.method=='POST': title=request.form.get("title") content=request.form.get("content") gid=request.form.get("gid") update_time=datetime.datetime.now() article=Article.query.get(article_id) article.title=title article.content=content print(content) article.gid=gid article.update_time=update_time try: db.session.commit() return redirect(url_for("front.article_manage")) except Exception: Flash (" modify %s failed "% title) return redirect(url_for("front.article_manage") @front.route('/delete_article/<int:article_id>') def delete_article(article_id): article=Article.query.get(article_id) try: Db.session.delete (article) db.session.com MIT () flash(" delete article %s succeeded "%article. Title) return db.session.delete(article) db.session.com MIT () flash(" delete article %s succeeded "%article redirect(url_for("front.article_manage")) except Exception: Flash (" delete article %s failed "%article.title) return redirect(url_for("front.article_manage"))Copy the code

8. User personal information logout module

Through this module, the user can log out the current login account with one key and return to the login page

@front.route('/logout') def logout(): Session.clear () flash(" Login succeeded ") return redirect(url_for('front.login'))Copy the code

9. Information management module

For the above module information need to be stored in the mysql database, first in the local mysql database to create a blog library, and then execute the Web project, this module will map the database table information and database table to create, and assign the corresponding type.

Login_manager = LoginManager() db=SQLAlchemy() class User(db.model,UserMixin) # __tablename__='login_register' ID = Column(db.Integer, Autoincrement =True,primary_key=True) # AUTOincrement Username =Column(db.string (50),nullable=False) password=Column(db.string (128),nullable=True) # {{users}} def __repr__(self): return self.username def get_id(self): return True class Article(db.model): __tablename__='article' id = db.Column(db.Integer, autoincrement=True, primary_key=True) title = db.Column(db.String(50), nullable=False,unique=True) content=db.Column(db.String(512),nullable=True) uid=db.Column(db.Integer,db.ForeignKey('user.id')) gid=db.Column(db.Integer,db.ForeignKey('article_group.id')) Create_time =db.Column(db.datetime) update_time=db.Column(db.datetime) users=db.relationship('User',backref=db.backref('articles')) groups=db.relationship('ArticleGroup',backref=db.backref('articles')) def __repr__(self): return '<Article %s>'%self.title class ArticleGroup(db.Model): __tablename__='article_group' id = db.Column(db.Integer, autoincrement=True, primary_key=True) name = db.Column(db.String(50), nullable=False,unique=True) color= db.Column(db.String(50), nullable=False) def __repr__(self): return '<ArticleGroup %s>'% self.name @login_manager.user_loader def get_user(user_id): Filler_by user = db.session.query(user).get(user_id) return userCopy the code

10. Program start module

In order to make Flask startup entry more brief, I encapsulated the startup module code

def create_app(): app=Flask(__name__) app.config.from_object('config') register_blueprint(app) db.init_app(app) Login_manager.init_app (app) login_manager.login_view="front. Login "login_manager.login_message_category=' Please login or register first ' db.create_all(app=app) return app def register_blueprint(app): from front_back import front app.register_blueprint(front)Copy the code

Application main class

From current import create_app app=create_app() if __name__ == '__main__': app.run(host='0.0.0.0',debug=True,port=83)Copy the code

Our blog here project related module will be written, there are a lot of friends you can add according to your demand, it is also a Flask of particular features of a place, here to explain that because of the front part of the code too much, here don’t display, I need a friend can be private to get the overall code yo.

11. Intranet penetration module

This module may be strange to many friends, so here is an example for them to understand.

When you say we’re going to deploy this project and make it available to everyone, the obvious thing is to use a server. However, the cost of the server is high, and the deployment process is also complicated, so is there any good way to help us achieve the local service ID mapping to the public network access? The answer is Intranet penetration

Here to introduce a quick Intranet penetration tool, peanut shell. You can directly go to search and download oh.

After downloading, we just need to input our local IP, and it will help us generate a domain name to realize public network access, as shown in the picture below.

Then go to the browser to test whether it is accessible:

12. To summarize

Here for blog preparation and Intranet penetration practice is over! Flask is easy to do in general, but the important thing is that when you want to learn something you stick to it, the hard work will pay off!