Python web framework Flask build static blog tutorial

Source: Internet
Author: User
Tags mkdir what php virtual environment virtualenv in python

There are many popular static blog/website generation tools, such as Jekyll, Pelican, Middleman, and Hyde. StaticGen lists some of the most popular static website generation tools.

Our internal tool is built by Python/Flask/MongoDB. Now we need to add the document function. The writing format is Markdown and we don't want to put the document into the database, I didn't want to get another static blog tool to manage documents, so I found the Flask-FlatPages easy-to-use Flask module. If you are familiar with Flask, you can build a simple blog in a few minutes. With the help of Bootstrap, you can use Flask-Flatpages to create a website in less than an hour.

Create a development environment

First, we need pip. The simplest installation method on Mac is:

$ Sudo easy_install pip
$ Sudo easy_install virtualenv

If you use the Homebrew package management tool on Mac, you can also use brew to upgrade Python and install pip:

$ Brew update
$ Brew install python

Create a blog Directory, generate an independent Python virtual environment, and install the required Flask and Flask-FlatPages modules in this environment:

$ Mkdir blog
$ Cd blog

$ Virtualenv flask
New python executable in flask/bin/python
Installing setuptools, pip... done.

$ Flask/bin/pip install flask
$ Flask/bin/pip install flask-flatpages

Under the blog Directory, we create several directories: static to store css/js files, templates to store the Jinja2 template for flask, and pages to store our static blog (Markdown format ):

$ Mkdir-p app/static app/templates app/pages

Program

The main program's blog. py function is to import necessary modules, configure parameters required by the Flask-FlatPages module, create a Flask application, write several URL routing functions, and finally run the application:

$ Vi app/blog. py
#! Flask/bin/python
From flask import Flask, render_template
From flask_flatpages import FlatPages

DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '. MS'

App = Flask (_ name __)
App. config. from_object (_ name __)
Flatpages = FlatPages (app)

@ App. route ('/')
Def index ():
Pages = (p for p in flatpages if 'date' in p. meta)
Return render_template('index.html ', pages = pages)

@ App. route ('/pages/<path: path> /')
Def page (path ):
Page = flatpages. get_or_404 (path)
Return render_template('page.html ', page = page)

If _ name _ = '_ main __':
App. run (port = 8000)

Template

Generating HTML directly in Python is cumbersome and not fun (that was what PHP did in the 1990s s). In modern society, we use the template engine and Flask has automatically configured the Jinja2 template, use render_template () to render the template. By default, Flask searches for templates in the templates Directory. You only need to create several template files. Here we create base.html, index.html, and page.html.

$ Vi app/templates/base.html
<! Doctype html>
<Html>
<Head>
<Meta charset = "utf-8">
<Title> vpsee.com static blog </title>
</Head>

<Body>
<H1> <a href = "{url_for (" index ") }}"> vpsee.com blog </a> {% Block content %}
{% Endblock content %}
</Body>
</Html>

In the code, extends base.html refers to inheriting the basic "skeleton" from base.html ".

$ Vi app/templates/index.html
{% Extends "base.html" %}

{% Block content %}
<H2> List of pages
<Ul>
{% For page in pages %}
<Li>
<A href = "{url_for (" page ", path = page. path) }}" >{{ page. title }}</a>
</Li>
{% Else %}
<Li> No post. </li>
{% Endfor %}
</Ul>
{% Endblock content %}

$ Vi app/templates/page.html
{% Extends "base.html" %}

{% Block content %}
<H2 >{{ page. title }}{Page.html | safe }}
{% Endblock content %}

The Flask-FlatPages module searches for the Markdown document ending with. md from the pages directory by default. Therefore, we put the content of static blogs in this directory:

$ Vi app/pages/hello-world.md
Title: Hello World
Date: 2014-10-14
Tags: [general, blog]

** Hello World **!

$ Vi app/pages/test-flatpages.md
Title: Test Flask FlatPages
Date: 2014-10-15
Tags: [python, flask]

Test [Flask-FlatPages] (https://pythonhosted.org/Flask-FlatPages)

Run

Basically, run the command to see the effect:

$ Flask/bin/python app/blog. py
* Running on http: // 127.0.0.1: 8000/
* Restarting with reloader



Static

So far, the above blog has run well, but there is a problem. This blog is not "static" and has not generated any html files, it cannot be used directly on a web server such as nginx or apache. So we need help from another Flask module Frozen-Flask.

Install Frozen-Flask:

$ Flask/bin/pip install frozen-flask

Modify blog. py, import the Flask-Frozen module, initialize Freezer, and use freezer. freeze () to generate static HTML:

$ Vi app/blog. py
...
From flask_flatpages import FlatPages
From flask_frozen import Freezer
Import sys
...
Flatpages = FlatPages (app)
Freezer = Freezer (app)
...
If _ name _ = '_ main __':
If len (sys. argv)> 1 and sys. argv [1] = "build ":
Freezer. freeze ()
Else:
App. run (port = 8000)

After running blog. py build, the build directory is generated under the app directory. The build directory contains the HTML static file we want:

$ Flask/bin/python app/blog. py build

$ Ls app/
Blog. py build pages static templates

The clearer directory structure is as follows:

$ Tree app
App
── Blog. py
── Build
│ ── Index.html
│ ── Pages
│ ── Hello-world
│ ── Index.html
│ ── Test-flatpages
│ ── Index.html
── Pages
│ ── Hello-world.md.
│ ── Test-flatpages.md.
── Static
└ ── Templates
├ ── Base.html
── Index.html
└ ── Page.html

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.