Install Python: You need to install python on the Rpi OS. If not already installed, the process should depend upon the OS you are using. I found this in a google search.
To check if its installed, enter python
in terminal. It should start the interactive python shell if installed.
If you are installing python anew. Once its done check if pip was installed with python. 'which pip' should give you the path of installed pip. If not, sudo easy_install pip
should do.
Install Flask: Flask is a microframework for python. Django is good, but might be overkill for what you want to do. Flask is easy to learn(opinion) and light.
once python and related package managers are installed you can either run sudo pip install Flask
or sudo easy_install Flask
in the RPi terminal.
Sample Flask app: This simple flask form should get you started. This shows you how to make and submit forms. How to use templates to make good looking pages. And how to run the flask app on any port.
The directory structure will be like this.
+AppDir
|-myapp.py
|+templates
|-form.html
myapp.py
from datetime import datetime
from flask import Flask
app = Flask(__name__)
@app.route('/writetofile' methods = ['GET', 'POST'])
def writetofile():
if request.method == 'GET':
now = str(datetime.now())
data = {'name' : request.args['name'], 'date' : now, 'filled':False}
return render_template('form.html', data=data)
if request.method == 'POST':
content = request.params['content']
now = str(datetime.now())
with open('samplefile.txt', 'w') as f:
f.write(content)
data = {'filled':True, 'file': 'samplefile.txt', 'date': now}
return render_template('form.html', date=date)
if __name__ == '__main__':
port = 8000 #the custom port you want
app.run(host='0.0.0.0', port=port)
form.html
<html><body>
<center>
<h2>Form</h2>
<p>Welcome, Current system DateTime is {{data.date}}.</p>
{% if data.filled %}
<p>Your content has been written to {{ data.file }}</p>
{% endif %}
<form action="{{ url_for('writetofile') }}" method=post>
<label>What do you want to write to the file?</lable>
<textarea name=content cols=60 rows=10 placeholder='Write here > Press submit'>
</textarea>
<input type=submit value='Lets Go!'>
</form>
</center>
</html></body>
Run the App : Once you are done with the setup, open the RPi terminal, cd <path/to/AppDir>
then python myapp.py
Open any browser on your system and goto http://<yourRPi address>:8000/writetofile
.
More things to do:
1. Learn to run commands on screen
. It runs a processes in the background. It is required now because when your ssh connection breaks, the flask server will shutdown if it is not running in the background.
Figure Out which config files you want to change.
Figure out which system config or functions you want to control with flask URLs, you can use subprocess module to run terminal commands from python.
Learn how to deploy flask using Gunicorn. Not very important at the moment. Flask's inbuilt server becomes unresponsive at times when it is running more 1-2 days.