Browse Source

Web now covers Flask instead of Bottle

pull/152/head
Jure Šorn 1 year ago
parent
commit
80ffe84187
2 changed files with 52 additions and 46 deletions
  1. 45
      README.md
  2. 53
      index.html

45
README.md

@ -2525,49 +2525,50 @@ except requests.exceptions.ConnectionError:
Web
---
**Bottle is a micro web framework/server. If you just want to open a html file in a web browser use `'webbrowser.open(<path>)'` instead.**
**Flask is a micro web framework/server. If you just want to open a html file in a web browser use `'webbrowser.open(<path>)'` instead.**
```python
# $ pip3 install bottle
from bottle import run, route, static_file, template, post, request, response
import json
# $ pip3 install flask
from flask import Flask, send_from_directory, render_template_string, request
```
### Run
```python
run(host='localhost', port=8080) # Runs locally.
run(host='0.0.0.0', port=80) # Runs globally.
app = Flask(__name__)
app.run()
```
* **Starts the app on `'http://localhost:5000'`.**
* **You will need a WSGI server like [waitress](https://flask.palletsprojects.com/en/latest/deploying/waitress/) and a HTTP server such as [nginx](https://flask.palletsprojects.com/en/latest/deploying/nginx/) to run globally.**
### Static Request
```python
@route('/img/<filename>')
def send_file(filename):
return static_file(filename, root='img_dir/')
@app.route('/img/<path:filename>')
def serve_file(filename):
return send_from_directory('dirname/', filename)
```
### Dynamic Request
```python
@route('/<sport>')
def send_html(sport):
return template('<h1>{{title}}</h1>', title=sport)
@app.route('/<sport>')
def serve_html(sport):
return render_template_string('<h1>{{title}}</h1>', title=sport)
```
* **`'render_template()'` accepts filename of a template stored in 'templates' directory.**
### REST Request
```python
@post('/<sport>/odds')
def send_json(sport):
team = request.forms.get('team')
response.headers['Content-Type'] = 'application/json'
response.headers['Cache-Control'] = 'no-cache'
return json.dumps({'team': team, 'odds': [2.09, 3.74, 3.68]})
@app.route('/<sport>/odds', methods=['POST'])
def serve_json(sport):
team = request.form['team']
return {'team': team, 'odds': [2.09, 3.74, 3.68]}
```
* **To get a parameter from the query string (part after the ?) use `'request.args.get(<str>)'`.**
#### Test:
```python
# $ pip3 install requests
>>> import threading, requests
>>> threading.Thread(target=run, daemon=True).start()
>>> url = 'http://localhost:8080/football/odds'
>>> threading.Thread(target=app.run, daemon=True).start()
>>> url = 'http://localhost:5000/football/odds'
>>> request_data = {'team': 'arsenal f.c.'}
>>> response = requests.post(url, data=request_data)
>>> response.json()
@ -2577,7 +2578,7 @@ def send_json(sport):
Profiling
---------
### Stopwatch
```python
from time import perf_counter
start_time = perf_counter()

53
index.html

@ -2071,50 +2071,55 @@ WIKI_URL = <span class="hljs-string">'https://en.wikipedia.org/wiki/Python_(prog
</code></pre></div></div>
<div><h2 id="web"><a href="#web" name="web">#</a>Web</h2><p><strong>Bottle is a micro web framework/server. If you just want to open a html file in a web browser use <code class="python hljs"><span class="hljs-string">'webbrowser.open(&lt;path&gt;)'</span></code> instead.</strong></p><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install bottle</span>
<span class="hljs-keyword">from</span> bottle <span class="hljs-keyword">import</span> run, route, static_file, template, post, request, response
<span class="hljs-keyword">import</span> json
<div><h2 id="web"><a href="#web" name="web">#</a>Web</h2><p><strong>Flask is a micro web framework/server. If you just want to open a html file in a web browser use <code class="python hljs"><span class="hljs-string">'webbrowser.open(&lt;path&gt;)'</span></code> instead.</strong></p><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install flask</span>
<span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, send_from_directory, render_template_string, request
</code></pre></div>
<div><h3 id="run">Run</h3><pre><code class="python language-python hljs">run(host=<span class="hljs-string">'localhost'</span>, port=<span class="hljs-number">8080</span>) <span class="hljs-comment"># Runs locally.</span>
run(host=<span class="hljs-string">'0.0.0.0'</span>, port=<span class="hljs-number">80</span>) <span class="hljs-comment"># Runs globally.</span>
</code></pre></div>
<div><h3 id="staticrequest">Static Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@route('/img/&lt;filename&gt;')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_file</span><span class="hljs-params">(filename)</span>:</span>
<span class="hljs-keyword">return</span> static_file(filename, root=<span class="hljs-string">'img_dir/'</span>)
<pre><code class="python language-python hljs">app = Flask(__name__)
app.run()
</code></pre>
<ul>
<li><strong>Starts the app on <code class="python hljs"><span class="hljs-string">'http://localhost:5000'</span></code>.</strong></li>
<li><strong>You will need a WSGI server like <a href="https://flask.palletsprojects.com/en/latest/deploying/waitress/">waitress</a> and a HTTP server such as <a href="https://flask.palletsprojects.com/en/latest/deploying/nginx/">nginx</a> to run globally.</strong></li>
</ul>
<div><h3 id="staticrequest">Static Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@app.route('/img/&lt;path:filename&gt;')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">serve_file</span><span class="hljs-params">(filename)</span>:</span>
<span class="hljs-keyword">return</span> send_from_directory(<span class="hljs-string">'dirname/'</span>, filename)
</code></pre></div>
<div><h3 id="dynamicrequest">Dynamic Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@route('/&lt;sport&gt;')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_html</span><span class="hljs-params">(sport)</span>:</span>
<span class="hljs-keyword">return</span> template(<span class="hljs-string">'&lt;h1&gt;{{title}}&lt;/h1&gt;'</span>, title=sport)
<div><h3 id="dynamicrequest">Dynamic Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@app.route('/&lt;sport&gt;')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">serve_html</span><span class="hljs-params">(sport)</span>:</span>
<span class="hljs-keyword">return</span> render_template_string(<span class="hljs-string">'&lt;h1&gt;{{title}}&lt;/h1&gt;'</span>, title=sport)
</code></pre></div>
<div><h3 id="restrequest">REST Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@post('/&lt;sport&gt;/odds')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_json</span><span class="hljs-params">(sport)</span>:</span>
team = request.forms.get(<span class="hljs-string">'team'</span>)
response.headers[<span class="hljs-string">'Content-Type'</span>] = <span class="hljs-string">'application/json'</span>
response.headers[<span class="hljs-string">'Cache-Control'</span>] = <span class="hljs-string">'no-cache'</span>
<span class="hljs-keyword">return</span> json.dumps({<span class="hljs-string">'team'</span>: team, <span class="hljs-string">'odds'</span>: [<span class="hljs-number">2.09</span>, <span class="hljs-number">3.74</span>, <span class="hljs-number">3.68</span>]})
<ul>
<li><strong><code class="python hljs"><span class="hljs-string">'render_template()'</span></code> accepts filename of a template stored in 'templates' directory.</strong></li>
</ul>
<div><h3 id="restrequest">REST Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@app.route('/&lt;sport&gt;/odds', methods=['POST'])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">serve_json</span><span class="hljs-params">(sport)</span>:</span>
team = request.form[<span class="hljs-string">'team'</span>]
<span class="hljs-keyword">return</span> {<span class="hljs-string">'team'</span>: team, <span class="hljs-string">'odds'</span>: [<span class="hljs-number">2.09</span>, <span class="hljs-number">3.74</span>, <span class="hljs-number">3.68</span>]}
</code></pre></div>
<ul>
<li><strong>To get a parameter from the query string (part after the ?) use <code class="python hljs"><span class="hljs-string">'request.args.get(&lt;str&gt;)'</span></code>.</strong></li>
</ul>
<div><h4 id="test">Test:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install requests</span>
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> threading, requests
<span class="hljs-meta">&gt;&gt;&gt; </span>threading.Thread(target=run, daemon=<span class="hljs-keyword">True</span>).start()
<span class="hljs-meta">&gt;&gt;&gt; </span>url = <span class="hljs-string">'http://localhost:8080/football/odds'</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>threading.Thread(target=app.run, daemon=<span class="hljs-keyword">True</span>).start()
<span class="hljs-meta">&gt;&gt;&gt; </span>url = <span class="hljs-string">'http://localhost:5000/football/odds'</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>request_data = {<span class="hljs-string">'team'</span>: <span class="hljs-string">'arsenal f.c.'</span>}
<span class="hljs-meta">&gt;&gt;&gt; </span>response = requests.post(url, data=request_data)
<span class="hljs-meta">&gt;&gt;&gt; </span>response.json()
{<span class="hljs-string">'team'</span>: <span class="hljs-string">'arsenal f.c.'</span>, <span class="hljs-string">'odds'</span>: [<span class="hljs-number">2.09</span>, <span class="hljs-number">3.74</span>, <span class="hljs-number">3.68</span>]}
</code></pre></div>
<div><h2 id="profiling"><a href="#profiling" name="profiling">#</a>Profiling</h2><div><h3 id="stopwatch">Stopwatch</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> perf_counter
<div><h2 id="profiling"><a href="#profiling" name="profiling">#</a>Profiling</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> perf_counter
start_time = perf_counter()
...
duration_in_seconds = perf_counter() - start_time
</code></pre></div></div>
</code></pre></div>
<div><h3 id="timingasnippet">Timing a Snippet</h3><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> timeit <span class="hljs-keyword">import</span> timeit
<span class="hljs-meta">&gt;&gt;&gt; </span>timeit(<span class="hljs-string">"''.join(str(i) for i in range(100))"</span>,

Loading…
Cancel
Save