0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Flask-Python实现简单网页

Posted at

例子1:最简单的web启动

最简单实现helloworld

hello.py
# start source block
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
	return 'Hello World!'

def main():
	# 开发用web服务器启动
	app.run(host='127.0.0.1', port=5678, debug=False)


if __name__ == '__main__':
	# 调用main启动函数
	main()
# end source block

上面代码保存为hello.py
命令行运行 $ python hello.py
在浏览器访问地址:http://localhost:5678
正常页面显示 Hello World!

例子2:Blueprint启动views目录下的py文件和html模板

目录结构

hello/
--app.py
--views/
----init.py # 作为软件包定义
----view_hello.py
--templates/
----view_hello.html

主启动app.py文件

app.py
# start source block
from flask import (
    Flask,
    Blueprint,
)

# 导入目标页面的view
from views import view_hello

app = Flask(__name__)

# 注册目标页面的子app 所有对象页面都会在根地址root_url/hello/出现
app.register_blueprint(view_hello.app, url_prefix='/hello')


def main():
    # 开发用web服务器启动
    app.run(host='127.0.0.1', port=5678, debug=False)


if __name__ == '__main__':
    # 调用main启动函数
    main()
# end source block

html数据先是用服务器端处理view_hello.py

view_hello.py
# start source block
from flask import (
    Flask,
    Blueprint,
    render_template,
)

app = Blueprint(
    'views.hello',
    __name__,
    template_folder='templates',
)


@app.route('/sayhello')
def say_hello():
    page_title = 'hello world'
    page_html = 'view_hello.html'

    res = {
        'page_title': page_title,
        # 'data_lst': data_lst, 其他页面表示数据
    }

    return render_template(
        page_html,
        res=res,
    )
# end source block

__init__.py
# start source block
# package
# 只有注释
# end source block

前端表示用view_hello.html

view_hello.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>{{res.page_title}}</title>

  </head>
  <body >
你好 世界!   
  </body>
</html>

命令行运行 $ python app.py
在浏览器访问地址:http://localhost:5678/hello/sayhello
正常页面显示 标题:hello world! 页面内容:你好 世界!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?