python code for website development


source:Mai Shu Programming


Develop a simple website system containing the database isWebThe best way to develop entry。

FlaskYesPythonMost popular twoWebOne of the frames,It is the easiest to use,Easy to get started。

This series is usedPythonofFlaskFrame development a simple blog system,Sharing90minute。The whole article is divided into3part,Today is the first「2」part。First3Part of this Sunday released。

Original plan is divided into2part,A little length,Temporarily changed3part。

First1Part of the link:

It's time to studyWebdeveloped!1UsePythonDevelopment blog system【1】

The entire article includes the following,First1Part of it covers5part,Today contains the middle3part:

  1. Installflask
  2. Create a project
  3. Run your first website
  4. Create a decent web page
  5. Use style to beautify web pages
  6. 「Use templates andbootstrap」
  7. 「Create a document database」
  8. 「Display all articles」
  9. Show an article
  10. Release new article
  11. Modify article content
  12. Delete articles
  13. About Mai Shushan
(python code for website development)Today's article is a bit big,All source code can pay attention to the public number「Mai Shu Programming」,Reply「fff」Get a link。

let us start!Last week we have already createdflaskProgram and an application of basic style:

(python code for website development)python code for website development

one、Use templates andBootstrap

We have to continue「beautify」page。

Most websites have a lot of pages,These pages share the same menu bar。You can't develop no pages, you have to write the menu bar over.?

Here is used here.「template」the concept of,We create a template,The template contains a common part of the menu.,And the specific page will fill in the template.。

Our blog final style is like this,It contains「List」「New construction」「Detail」「Revise」「About Mai Shu」Multiple pages。These pages share the same template。

(python code for website development)python code for website development


(python code for website development)We need to usejqueryandbootstrap,Go to me firstgitUpload these documents,Download method:Follow Mai Shusu Programming,Reply210820。

After the download is finished,staticDirectorycssandjsUnder contents。injsDirectory needs to be created first。

(python code for website development)python code for website development

2.existtemplatesCreate a new file in the directory:base.html

<!doctype html>
<html lang="en">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="{{ url_for('static', filename= 'css/bootstrap.min.css') }}">
    <title>{% block title %} {% endblock %}</title>
    <nav class="navbar navbar-expand-md navbar-light bg-light">
        <a class="navbar-brand" href="{{ url_for('index')}}">Mai Shu's blog</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>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
            <li class="nav-item active">
                <a class="nav-link" href="#">About Mai Shu</a>
    <div class="container">
        {% block content %} {% endblock %}

    <script src="{{url_for('static', filename='js/jquery.slim.min.js')}}" ></script>
    <script src="{{url_for('static', filename='js/popper.min.js')}}" ></script>
    <script src="{{url_for('static', filename='js/bootstrap.min.js')}}" ></script>


This is a bit large,I will explain one by one.:

python code for website development

  1. Reviseindex.htmlIn the content{% extends 'base.html' %}
    {% block content %}
    <h1>{% block title %} Welcome to the blog of Mai Shu {% endblock %}</h1>
    {% endblock %}
  2. first rowextends 'base.html'Indicates that we have to use the previous definitionbase.htmlThis template。To use this template,Just put two placeholders in the template(Two filled questions)Fill in。
  3. Put in{% block content %}and{% endblock %}All content in the middle will be filled incontentIn this placeholder。
  4. Put in{% block title %}and{% endblock %}The intermediate content will be filled intitlePlaceholder。Note that heretitleVariables will be reused。It is bothtitleContents of placeholders,ToocontentPart of the placeholder。
  5. refresh page,It should be seen as follows。if not,Carefully check where to miss it.,Or spelling errors。Although there is no big change here,But we have already built templates,The content developed later can reuse this template,And the page itself will become very simple.。

two、Create a document database

There are many articles in bloggers.,We have to save these articles to the database。

(python code for website development)There are many options in the database,for exampleMySQL, postgresql,Oracle, sqlite3Wait。

We want to use the lightest level database today.sqlite3,PythonBring this library,So don't need additional installation。

  1. existblog.pyCreate a file in the same directorydb.sql,It is a database table for creating a database table.SQLStatement:DROP TABLE IF EXISTS posts;
    CREATE TABLE posts (
    title TEXT NOT NULL,
    content TEXT NOT NULL
  2. First lookpostsWhether the table exists,if it exists,Remove it first。
  3. Create a namepostsTable,It containsid,title,contentAnd create time(created)Wait。
  4. existblog.pyCreate a file in the same directoryinit_db.pyThis is apythonCode file,It is connected tosqlitedatabase,Ongoingdb.sqlStatement,Then insert two articles。See the specific details:import sqlite3
    # Create a database link
    connection = sqlite3.connect('database.db')
    # implementdb.sqlmiddleSQLStatement
    with open('db.sql') as f:
    # Create an execution handle,Used to perform the following statement
    cur = connection.cursor()
    # Insert two articles
    cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)",
    ('LearnFlask1', 'Mai Shuflaskfirst part')
    cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)",
    ('LearnFlask2', 'Mai Shuflaskthe second part')
    # Submit the previous data operation
    # Close link
  5. Open a command line,runinit_db.pyIf there is no error,I will find more than the folder.database.db,This is the database file。

three、Display article list

(python code for website development)There are two articles in the database,We can usepythonGet data from the database,And display on the webpage。

  1.,See the specific detailsimport sqlite3 #Introducesqlite3
    from flask import Flask, render_template
    app = Flask(__name__)
    # Create a function to get database links
    def get_db_connection():
    # Create a database link todatabase.dbdocument
    conn = sqlite3.connect('database.db')
    # Set data analysis method,Have this setting,You can access each column data like a dictionary.
    conn.row_factory = sqlite3.Row
    return conn
    def index():
    # Call the above function,Get link
    conn = get_db_connection()
    # Query all data,Put into variablespostsmiddle
    posts = conn.execute('SELECT * FROM posts').fetchall()
    #QuerypostsPass to the web
    return render_template('index.html', posts=posts)
    def about():
    return render_template('about.html')
  2. Reviseindex.htmlOnly one title was shown before.,Now you want to cycleblog.pyPassingpostsList,Show each article out。NoticeforCycling in the page,andpythonCode is very similar,Just use{%and%}wrap up。{% extends 'base.html' %}
    {% block content %}
    <h1>{% block title %} Welcome to the blog of Mai Shu {% endblock %}</h1>
    {% for post in posts %}
    <a href="#">
    <h2>{{ post['title'] }}</h2>
    <span class="badge badge-primary">{{ post['created'] }}</span>
    {% endfor %}
    {% endblock %}
  3. refresh page,You should see such an effect:if not,Careful comparison,Look at what is less or if there is any spelling error。

I am here today.,The following part will be released on this Sunday,I will also send a video at that time.bilibili,Please keep attention。

(python code for website development)The entire article includes the following,First1Part of it covers5part,Today, the following part:

  1. Installflask
  2. Create a project
  3. Run your first website
  4. Create a decent web page
  5. Use style to beautify web pages
  6. Use templates andbootstrap
  7. Create a document database
  8. Display all articles
  9. 「Show an article」
  10. 「Release new article」
  11. 「Modify article content」
  12. 「Delete articles」
  13. About Mai Shushan

website development company american fork


website development company american fork Florida, USA,What is the cost of a dynamic e-commerce website??At the data exitWe are e-commerce website designersThe company provides the best professional web design for small or large companies in

quality management plan for website development


quality management plan for website development Website as a facade in the Internet promotion,Is the display of corporate image,The importance is self-evident。So how to build a high quality website?What issues need to pay attention to during websit

how to choose website development company


how to choose website development company In today's fast-developing economy,Small and medium-sized enterprises have realized the importance of enterprise website to enterprise development。However,The website building market is polarized。Some