Deployment of Writing Static html Pages to the Web Server
Categories: Tech | Pubby Cash Received:
In the previous post titled "How to Make Static .html Pages Accessible with Flask in Python", we've solved the obstacle of html accessibility. Now the question becomes: how to make those static html pages?
The basic idea is to query the database to generate these html pages and then save these html pages to the static "html" folder. To do this, we will need to use the BeautifulSoup module I've introduced in the an earlier post. First, we try to request the pages from the web server one at a time based on the article id of each page. Then we will parse the response from the server with the BeautifulSoup module. Since the result is the BeautifulSoup class, we will need to convert it to a string, and then write the string into a html file.
The tricky parts are: (1) how to write to a file if the file does not exit? (2) how to avoid the character code error (e.g. a gbk code error might be thrown out) during the writing? and (3) how to make the process efficient by not re-writing the files again and again?
For the first part, I could use
with open('file_name', 'w') as file:
file.write()
For the second part, however, the above code will not work. To solve the character code error, I will need to import the io module, and re-write the above code like this:
with io.open('file_name', 'w', encoding='utf-8') as file:
file.write()
For the third part, I let a script auto-run in the background with a nested loop. In the inner loop, I query the most recent posts published during the week and only write those new files. In the outer loop, such queries and writings are controlled to be run once a week.
Want to see a showcase? Access my last post via this static html page!
http://gopubby.com/html/173.html
Published from: Pennsylvania US
Liked by: Andy Tang, Evan Tang, fnfOzvSR