怎么使用python flask搭建静态服务器

怎么使用python flask搭建静态服务器,第1张

Frozen-Flask freezes a Flask application into a set of static files. The result can be hosted without any server-side software other than a traditional web server.

Note: This project used to be called Flask-Static.

Installation

Install the extension with one of the following commands:

$ easy_install Frozen-Flask

or alternatively if you have pip installed:

$ pip install Frozen-Flask

or you can get the source code from github.

Context

This documentation assumes that you already have a working Flask application. You can run it and test it with the development server:

from myapplication import appapp.run(debug=True)

Frozen-Flask is only about deployment: instead of installing Python, a WGSI server and Flask on your server, you can use Frozen-Flask to freeze your application and only have static HTML files on your server.

Getting started

Create a Freezer instance with your app object and call its freeze() method. Put that in a freeze.py script (or call it whatever you like):

from flask_frozen import Freezerfrom myapplication import appfreezer = Freezer(app)if __name__ == '__main__':

freezer.freeze()

This will create a build directory next to your application’s static and templatesdirectories, with your application’s content frozen into  static files.

Note

Frozen-Flask considers it “owns” its build directory. By default, it will silently overwrite files in that directory, and remove those it did not create.

The configuration allows you to change the destination directory, or control what files are removed if at all.

This build will most likely be partial since Frozen-Flask can only guess so much about your application.

Finding URLs

Frozen-Flask works by simulating requests at the WSGI level and writing the responses to aptly named files. So it needs to find out which URLs exist in your application.

The following URLs can be found automatically:

Static files handled by Flask for your application or any of its blueprints.

Views with no variable parts in the URL, if they accept the GET method.

New in version 0.6: Results of calls to flask.url_for() made by your application in the request for another URL. In other words, if you use url_for() to create links in your application, these links will be “followed”.

This means that if your application has an index page at the URL / (without parameters) and every other page can be found from there by recursively following links built with url_for(), then Frozen-Flask can discover all URLs automatically and you’re done.

Otherwise, you may need to write URL generators.

URL generators

Let’s say that your application looks like this:

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

   return render_template('index.html', products=models.Product.all())@app.route('/product_<int:product_id>/')def product_details():

   product = models.Product.get_or_404(id=product_id)

   return render_template('product.html', product=product)

If, for some reason, some products pages are not linked from another page (or these links are not built by url_for()), Frozen-Flask will not find them.

To tell Frozen-Flask about them, write an URL generator and put it after creating your Freezer instance and before calling freeze():

@freezer.register_generatordef product_details():

   for product in models.Product.all():

       yield {'product_id': product.id}

Frozen-Flask will find the URL by calling url_for(endpoint, **values) whereendpoint is the name of the generator function and values is each dict yielded by the function.

You can specify a different endpoint by yielding a (endpoint, values) tuple instead of just values, or you can by-pass url_for and simply yield URLs as strings.

Also, generator functions do not have to be Python generators using yield, they can be any callable and return any iterable object.

All of these are thus equivalent:

@freezer.register_generatordef product_details():  # endpoint defaults to the function name

   # `values` dicts

   yield {'product_id': '1'}

   yield {'product_id': '2'}@freezer.register_generatordef product_url_generator():  # Some other function name

   # `(endpoint, values)` tuples

   yield 'product_details', {'product_id': '1'}

   yield 'product_details', {'product_id': '2'}@freezer.register_generatordef product_url_generator():

   # URLs as strings

   yield '/product_1/'

   yield '/product_2/'@freezer.register_generatordef product_url_generator():

   # Return a list. (Any iterable type will do.)

   return [

       '/product_1/',

       # Mixing forms works too.

       ('product_details', {'product_id': '2'}),

   ]

Generating the same URL more than once is okay, Frozen-Flask will build it only once. Having different functions with the same name is generally a bad practice, but still work here as they are only used by their decorators. In practice you will probably have a module for your views and another one for the freezer and URL generators, so having the same name is not a problem.

Testing URL generators

The idea behind Frozen-Flask is that you can use Flask directly to develop and test your application. However, it is also useful to test your URL generators and see that nothing is missing, before deploying to a production server.

You can open the newly generated static HTML files in a web browser, but links probably won’t work. The FREEZER_RELATIVE_URLS configuration can fix this, but adds a visible index.html to the links. Alternatively, use the run() method to start an HTTP server on the build result, so you can check that everything is fine before uploading:

if __name__ == '__main__':

   freezer.run(debug=True)

Freezer.run() will freeze your application before serving and when the reloader kicks in. But the reloader only watches Python files, not templates or static files. Because of that, you probably want to use Freezer.run() only for testing the URL generators. For everything else use the usual app.run().

Flask-Script may come in handy here.

Controlling What Is Followed

Frozen-Flask follows links automatically or with some help from URL generators. If you want to control what gets followed, then URL generators should be used with the Freezer’s with_no_argument_rules and log_url_for flags. Disabling these flags will force Frozen-Flask to use URL generators only. The combination of these three elements determines how much Frozen-Flask will follow.

Configuration

Frozen-Flask can be configured using Flask’s configuration system. The following configuration values are accepted:

FREEZER_BASE_URL

Full URL your application is supposed to be installed at. This affects the output of flask.url_for() for absolute URLs (with _external=True) or if your application is not at the root of its domain name. Defaults to 'http://localhost/'.

FREEZER_RELATIVE_URLS

If set to True, Frozen-Flask will patch the Jinja environment so that url_for() returns relative URLs. Defaults to False. Python code is not affected unless you use relative_url_for() explicitly. This enables the frozen site to be browsed without a web server (opening the files directly in a browser) but appends a visible index.html to URLs that would otherwise end with /.

New in version 0.10.

FREEZER_DEFAULT_MIMETYPE

The MIME type that is assumed when it can not be determined from the filename extension. If you’re using the Apache web server, this should match the DefaultTypevalue of Apache’s configuration.  Defaults to application/octet-stream.

New in version 0.7.

FREEZER_IGNORE_MIMETYPE_WARNINGS

If set to True, Frozen-Flask won’t show warnings if the MIME type returned from the server doesn’t match the MIME type derived from the filename extension. Defaults to False.

New in version 0.8.

FREEZER_DESTINATION

Path to the directory where to put the generated static site. If relative, interpreted as relative to the application root, next to the static and templates directories. Defaults to build.

FREEZER_REMOVE_EXTRA_FILES

If set to True (the default), Frozen-Flask will remove files in the destination directory that were not built during the current freeze. This is intended to clean up files generated by a previous call to Freezer.freeze() that are no longer needed. Setting this to False is equivalent to setting FREEZER_DESTINATION_IGNORE to ['*'].

New in version 0.5.

FREEZER_DESTINATION_IGNORE

A list (defaults empty) of fnmatch patterns. Files or directories in the destination that match any of the patterns are not removed, even if FREEZER_REMOVE_EXTRA_FILES is true. As in .gitignore files, patterns apply to the whole path if they contain a slash /, to each slash-separated part otherwise. For example, this could be set to ['.git

当我们执行下面的hello.py时,使用的flask自带的服务器,完成了web服务的启动。在生产环境中,flask自带的服务器,无法满足性能要求,我们这里采用Gunicorn做wsgi容器,来部署flask程序。Gunicorn(绿色独角兽)是一个Python WSGI的HTTP服务器。从Ruby的独角兽(Unicorn )项目移植。该Gunicorn服务器与各种Web框架兼容,实现非常简单,轻量级的资源消耗。Gunicorn直接用命令启动,不需要编写配置文件,相对uWSGI要容易很多。

区分几个概念

WSGI:全称是Web Server Gateway Interface(web服务器网关接口),它是一种规范,它是web服务器和web应用程序之间的接口。它的作用就像是桥梁,连接在web服务器和web应用框架之间。

uwsgi:是一种传输协议,用于定义传输信息的类型。

uWSGI:是实现了uwsgi协议WSGI的web服务器。

我们的部署方式: nginx + gunicorn + flask

web开发中,部署方式大致类似。简单来说,前端代理使用Nginx主要是为了实现分流、转发、负载均衡,以及分担服务器的压力。Nginx部署简单,内存消耗少,成本低。Nginx既可以做正向代理,也可以做反向代理。

正向代理 :请求经过代理服务器从局域网发出,然后到达互联网上的服务器。

特点 :服务端并不知道真正的客户端是谁。

反向代理 :请求从互联网发出,先进入代理服务器,再转发给局域网内的服务器。

特点 :客户端并不知道真正的服务端是谁。

区别 :正向代理的对象是客户端。反向代理的对象是服务端。

查看命令行选项 : 安装gunicorn成功后,通过命令行的方式可以查看gunicorn的使用信息。

直接运行

指定进程和端口号 : -w: 表示进程(worker)。 -b:表示绑定ip地址和端口号(bind)。--access-logfile:表示指定log文件的路径

作为守护进程后台运行

阿里云服务器默认安装到 /user/sbin/ 目录,进入目录,启动 ngnix:

Ubuntu 上配置 Nginx 也是很简单,不要去改动默认的 nginx.conf 只需要将/etc/nginx/sites-available/default文件替换掉就可以了。

新建一个 default 文件,添加以下内容:

修改完成后重启nginx即可。

Ubuntu 上配置 Nginx 另一种方法,cd 到 /etc/nginx/conf.d 文件夹,新建 xxx.conf 文件(xxx 可以是项目名,只要是 .conf 文件即可),写入以下内容:

需要监听 https 请求时,写入以下内容:


欢迎分享,转载请注明来源:夏雨云

原文地址:https://www.xiayuyun.com/zonghe/399261.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-19
下一篇2023-05-19

发表评论

登录后才能评论

评论列表(0条)

    保存