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 appapprun(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 freezepy script (or call it whatever you like):
from flask_frozen import Freezerfrom myapplication import appfreezer = Freezer(app)if __name__ == '__main__':
freezerfreeze()
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 06: Results of calls to flaskurl_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:
@approute('/')def products_list():return render_template('indexhtml', products=modelsProductall())@approute('/product_<int:product_id>/')def product_details():
product = modelsProductget_or_404(id=product_id)
return render_template('producthtml', 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():
@freezerregister_generatordef product_details():for product in modelsProductall():
yield {'product_id': productid}
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:
@freezerregister_generatordef product_details(): # endpoint defaults to the function name# `values` dicts
yield {'product_id': '1'}
yield {'product_id': '2'}@freezerregister_generatordef product_url_generator(): # Some other function name
# `(endpoint, values)` tuples
yield 'product_details', {'product_id': '1'}
yield 'product_details', {'product_id': '2'}@freezerregister_generatordef product_url_generator():
# URLs as strings
yield '/product_1/'
yield '/product_2/'@freezerregister_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 indexhtml to the links Alternatively, use the run() method to start an >if __name__ == '__main__':
freezerrun(debug=True)
Freezerrun() 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 Freezerrun() only for testing the URL generators For everything else use the usual apprun()
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 flaskurl_for() for absolute URLs (with _external=True) or if your application is not at the root of its domain name Defaults to '>
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 indexhtml to URLs that would otherwise end with /
New in version 010
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 07
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 08
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 Freezerfreeze() that are no longer needed Setting this to False is equivalent to setting FREEZER_DESTINATION_IGNORE to ['']
New in version 05
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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)