Flask入门--创建一个Flask应用

369 阅读1分钟

这是我参与8月更文挑战的第9天,活动详情查看:8月更文挑战

Flask是什么

百度百科中记载:Flask 是一个使用 Python 编写的轻量级 Web 应用框架。其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2 。Flask使用 BSD 授权。

维基百科 WSGI 的介绍:

Web服务器网关接口(Python Web Server Gateway Interface,缩写为WSGI)是为Python语言定义的Web服务器Web应用程序框架之间的一种简单而通用的接口。自从WSGI被开发出来以后,许多其它语言中也出现了类似接口。

准备工作

首先我们先安装flask(本文默认读者已经安装好了python)。

pip install flask

首先先创建一个目录比如名叫flask的目录,接着在当前目录下面创建statictemplates文件夹已经main.py文件,其结构类似如下:

flask

|-- static

-- templates

-- main.py

其中static存放web应用所需的静态资源,而templates存放的是页面文件(如.html文件)。以下是python main.py的代码:

from flask import Flask

app = Flask(__name__,static_url_path='/')

@app.route('/')
def hello():

    return 'hello world'

app.run()

目前没有写前端界面模板,运行后命令台得到如下显示:

  • Serving Flask app "main" (lazy loading)
  • Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead.
  • Debug mode: off
  • Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

访问http://127.0.0.1:5000/ 得到如下页面:

image.png

ok,现在第一步已经完成,接下来我们来渲染下前端页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
<h2><strong>hello world</strong></h2>
</body>
</html>

效果如下:

image.png

结语:至此我们已经初步了解了flask框架。