Writing in the front

It’s been a long time since I wrote zhihu articles, and I’m a little unfamiliar with it. I feel that the editor of Zhihu is not very easy to use, so I guess I can get used to it

In fact, there is a Segmentfault class in the forum before, but it has not been done, this time I happen to learn Flask, let’s use Flask development. I had already read Flask’s dog books, so I had some basic knowledge of Flask, but I felt that I wasn’t writing my own code and wanted to try it out, so I came up with the idea of using Flask to develop forums and improve the cleanliness of my code.

All the project directory in zhuanlan.zhihu.com/p/113539585

If something is wrong or there is a better solution, please advise us

Get into the business

First, create a Flask project in Pycharm, select Flask, and then the name of the forum (I chose AttributeError here because it’s too common in Python). :

If you are using another IDE, you can also create a folder, create a virtual environment, and then PIP Install Flask

Once created, delete the code in app.py that Pycharm automatically generated and create a folder named App in the root directory, then create a main folder in the app to prepare for using Flask’s blueprints.

Then move the static and Template folders generated by Pycharm to the app folder and create __init__.py in the app folder by typing the following code:

from flask import Flask  # import Flask


def create_app() :
    app = Flask(__name__)  # create app instance

    return app  # to return to the app

Copy the code

In create_app, we create a Flask instance called app and let the whole function return app. In the root directory app.py, we call the whole function to create the app:

If __name__ == '__main__': app.run() # Run the appCopy the code

Now, if we run app.py and access 127.0.0.1:5000, we’ll see that the page throws a 404 exception because we haven’t created any pages yet. Now, create __init__.py in the main folder to create a blueprint:

Blueprint('main', __name__) # Create a Blueprint named main from.import views # import viewCopy the code

__init__.py in the app folder:

def create_app(): App = Flask(__name__) # create app instance from. Main import main as main_bp # import blueprint app.register_blueprint(main_bp) # register blueprint to app Return app # Return appCopy the code

Now, you may not find views on your IDE, so let’s create views.py in the main folder:

Def index(): return '<h1>Welcome to AttributeError! </h1>' # returns the body of the pageCopy the code

Now run the program again and you should see Welcome to AttributeError! Yes, but very ugly. If you want to develop a decent forum, the page must look good. So I found Bootstrap-Flask, a Flask extension that integrates www.getbootstrap.com/. Type PIP install bootstrap-flask on the command line to install it.

Once installed, we’ll create a file in our app folder called extensions.py to instantiate all extensions:

Flask_bootstrap import Bootstrap = Flask Bootstrap() # instantiate the extensionCopy the code

However, bootstrap-Flask has not been initialized yet. We now initialize it in __init__.py:

from flask import Flask  # import Flask
from .extensions import *  Import the already instantiated extension


def create_app() :
    app = Flask(__name__)  # create app instance
    
    bootstrap.init_app(app)  Initialize the extension

    from .main import main as main_bp  # import blueprint
    app.register_blueprint(main_bp)  # Register blueprint to app

    return app  # to return to the app

Copy the code

Now, we should include it in the page, but the template that just returned a string is not suitable for large sites. We will create a main folder in the Templeates folder and add index.html to the main folder:

{% from 'bootstrap/nav.html' import render_nav_item %} {# import the built-in function of bootstrap-flask #}
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AttributeError</title>
    {{ bootstrap.load_css() }} {# bootstrap-flask built-in CSS #}
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="/">AttributeError</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
                {{render_nav_item('main.index', 'home ')}} {# render navigation links using bootstrap-flask built-in functions #}
            </ul>
          </div>
    </nav>
    <br>
    <div class="container">
        <h1>AttributeError</h1>
        <hr>
        <p>Welcome to AttributeError!</p>
    </div>
</body>
{{ bootstrap.load_js() }} {# bootstrap-flask built-in JavaScript #}
</html>
Copy the code

Now, let’s introduce templates in view functions:

from flask import render_template  # import render template function
from . import main  # import blueprint


@main.route('/')  # define route
def index() :
    return render_template('main/index.html')  Return to the rendered body of the page
Copy the code

Now run the program again and the interface will look much better:

However, when you change program code now, the changes are not reflected at run time and you have to re-run the program to do so. This is inconvenient for development, so let’s turn on Flask’s debug mode, which automatically refreshes the application when any code changes:

from app import create_app  # import create_app

app = create_app()  # create an app

if __name__ == '__main__':
    app.run(debug=True)  Run the app and enable debug mode

Copy the code

Now, rerun the program and the application can refresh in real time.

In our current application, we haven’t created the database yet, so we haven’t been able to develop the most important features of the forum, but we will. As you may have noticed, the current templates are so complex that it would be too much trouble to type each one once, so we’ll create a base template to solve this problem. Start by creating base.html, the base template, in the Templates folder, with the following code:

{% from 'bootstrap/nav.html' import render_nav_item %} {# import the built-in function of bootstrap-flask #}
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %} {# title block #}</title>
    {{ bootstrap.load_css() }} {# bootstrap-flask built-in CSS #}
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="/">AttributeError</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
                {{render_nav_item('main.index', 'home ')}} {# render navigation links using bootstrap-flask built-in functions #}
            </ul>
          </div>
    </nav>
    <br>
    {% block content %}{% endblock %} {# content block #}
</body>
{% block scripts %} {# JS code block #}
    {{ bootstrap.load_js() }} {# bootstrap-flask built-in JavaScript #}
{% endblock %}
</html>
Copy the code

Now we can use the base template to simplify index.html:

{% extends 'base.html' %} Base. HTML #}

{% block title %}AttributeError{% endblock %} {# define title #}

{% block content %} {# define content #}
    <div class="container">
        <h1>AttributeError</h1>
        <hr>
        <p>Welcome to AttributeError!</p>
    </div>
{% endblock %}
Copy the code

Maybe you went to the official website of Bootstrap and learned about the controls. They are mainly blue with varying degrees of gray. This color scheme certainly looks good, but many websites are using it and it can’t stand out the features of the website at all. Therefore, I further studied the custom Bootstrap, but since 4.0, it is required to customize Scss, which is not friendly to CSS white people like me, so I found bootstrap. build: bootstrap.build

I used this tool to create a custom yellow theme, which can be found on Github. To use custom CSS, you need to change base.html:

{% from 'bootstrap/nav.html' import render_nav_item %} {# import the built-in function of bootstrap-flask #}
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %} {# title block #}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='Bootstrap/bootstrap.css') }}"> {# introduce custom Bootstrap CSS #}
</head>
<! -... -->
{% block scripts %} {# JS code block #}
    {{ bootstrap.load_js() }} {# bootstrap-flask built-in JavaScript #}
{% endblock %}
</html>

Copy the code

Now if you refresh the web page, you may not see the changes, but we changed the primary color of Bootstrap without using it. We will use it later in development.

Well, that’s it for today. I put the code here on GitHub, if you don’t want to do it by hand, you can

git clone https://github.com/PythonSamZhang/AttributeError.git
Copy the code

after

git checkout f63784c
Copy the code

The last

pip install -r requirements.txt
Copy the code

GitHub Repository: github.com/PythonSamZh…

Custom Bootstrap CSS is also stored in /app/static/Bootstrap.

Write in the last

Because I am also a small white, so if there is any incorrect place please advise 🙂