Write static pages¶
Once your site is complete, you can choose to either serve it within your Flask app or write static HTML pages ready for publication on the web as a static site.
Almoststatic provides the write_static
method, which writes static pages to
the disk. It only writes the pages in the location that you specify.
It is up to you to publish your pages where needed and to copy your static contents.
The best way to write a static site is to create a small script. The core of the script should look like this:
import sys
import almoststatic
a = almoststatic.Almoststatic()
a.load_config()
STATIC_URL = '/'
MEDIA_PREFIX = 'media'
DESTINATION = './_static_site'
if len(sys.argv) > 1:
STATIC_URL = sys.argv[1]
print(STATIC_URL)
a.write_static(destination=DESTINATION,
media_prefix=MEDIA_PREFIX,
static_url=STATIC_URL)
a.write_json_meta(destination=DESTINATION)
The destination
parameter is the location where files will be written to on
your disk.
The static_url
parameter allows you to set the location of files starting from
your URL. For example, if your site is hosted at https://mystatic.example.com/my_pages/
,
static_url
will be /my_pages/
. If your pages will be read from the file system,
you should leave static_url
as an empty string so that URLs are treated as
relative. If files are located at the root of your domain, static_url
should be
/
because this optimizes browser cache.
In this case we added the capability to add static URL as argument to the script.
The media_prefix
parameter allows you to change the location of media files
from ‘/content/media’, which is the default in the development environment, to
the location where they will be in the static site.
Keep in mind that when write_static
is working, it changes the global variable
is_static
from False to True. So, if during development you have pages that
you don’t want to include in the static site, you can exclude them by
inspecting the value of that variable.
By default, write_static
writes all pages of the site. However, if needed,
you can choose the pages to write by setting the pages
parameter or the
out_pages
parameter.
There is also the write_json_meta
method that allows you to write a JSON file
containing all metadata for pages. This can be used to write some JavaScript on
the client side to access information about pages. However, Almoststatic always
writes a file called site_meta.json
on the root of the media
folder, so
this method is often not required.
If you wish, you can add to your script all you need to automate the publishing
of the site, such as client FTP commands or automatic copying of media files.
See flaskapp.py
in the sample folder to see automatic FTP publishing in action.