# hello.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<h1>Hello Word</h1>"
if __name__ == "__main__":
app.run()
$
python hello.py
# hello.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<h1>Hello Word</h1>"
@app.route("/error")
def error():
raise RuntimeError
if __name__ == "__main__":
app.run(debug=True)
# hello.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<h1>Hello Word</h1>"
if __name__ == "__main__":
app.run(port=5566)
@app.route("/users")
def get_users():
users = ["Maomao", "Alicia"]
resp = ["<p>{}</p>".format(user) for user in users]
resp = "\n".join(resp)
return resp
@app.route("/user/<name>")
def get_user_name(name):
return "<h1>Hello, {}!</h1>".format(name)
@app.route("/user/<int:uid>")
def get_user_id(uid):
if isinstance(uid, int):
return "<h1>Your ID: {}</h1>".format(uid)
return "<h1>ID should be int</h1>"
@app.route("/user/<path:path>")
def get_user_path(path):
return "<h1>Path: {}</h1>".format(path)
$
git clone https://github.com/win911/flask_class.git$
git checkout ba273f# hello.py
from time import sleep
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
sleep(10)
return "<h1>Hello Word</h1>"
@app.route("/test")
def test():
return "<h1>Test</h1>"
if __name__ == "__main__":
app.run(threaded=True, debug=True)
# hello.py
from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def index():
user_agent = request.headers.get("User-Agent")
user_name = request.args.get("name")
return "<p>Your browser is {}</p><p>Your name is {}</p>".format(user_agent, user_name)
if __name__ == "__main__":
app.run(threaded=True, debug=True)
#from flask import url_for
statistic_data = {}
@app.before_request
def statistic():
# request.path in [url_for("index"), url_for("get_statistic")]
if request.path in ["/", "/statistic"]:
return
statistic_data[request.path] = statistic_data.setdefault(request.path, 0) + 1
@app.route("/statistic")
def get_statistic():
return "statistic_data: {}".format(statistic_data)
@app.route("/buy/food")
def buy_food():
return "<p>Here is your food.</p>"
@app.route("/buy/drink")
def buy_drink():
return "<p>Here is your dirnk.</p>"
$
git clone https://github.com/win911/flask_class.git$
git checkout 48b438# hello.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<h1>Bad Request</h1>", 400
if __name__ == "__main__":
app.run(threaded=True, debug=True)
@app.route("/")
def index():
return "<h1>Redirect</h1>", 302, {"Location": "http://www.google.com"}
from flask import redirect
@app.route("/")
def index():
return redirect("http://www.google.com")
from flask import make_response
@app.route("/no_cookie")
def no_cookie():
response = make_response("<h1>This document doesn't carry a cookie!</h1>")
return response
@app.route("/has_cookie")
def has_cookie():
response = make_response("<h1>This document carries a cookie!</h1>")
response.set_cookie("answer", "42")
return response
from flask import Response
@app.route("/has_cookie")
def has_cookie():
data = "<h1>This document carries a cookie!</h1>"
headers = {}
headers["Set-Cookie"] = "answer=45"
return Response(data, headers=headers)
from flask import abort
def load_user(uid):
try:
uid = int(uid)
if uid == 1:
return "Maomao"
elif uid == 2:
return "Alicia"
except BaseException:
return
@app.route("/user/<uid>")
def get_user(uid):
user = load_user(uid)
if not user:
abort(400)
else:
return "<h1>Hello, {}!</h1>".format(user)
$
git clone https://github.com/win911/flask_class.git$
git checkout aea593# hello.py
from flask import Flask
from flask_script import Manager
#from flask.ext.script import Manager
app = Flask(__name__)
manager = Manager(app)
@app.route("/")
def index():
return "<h1>Hello Word</h1>"
if __name__ == "__main__":
manager.run()
$
python hello.py runserver$
python hello.py runserver --port 5566$
python hello.py runserver --host 0.0.0.0$
python hello.py shell$
python hello.py hello@manager.command
def hello():
"""Just say hello"""
print("hello")
$
git clone https://github.com/win911/flask_class.git$
git checkout 192fec<!-- templates/index.html -->
<h1>Hello World!</h1>
<!-- templates/user.html -->
<h1>Hello, {{ name }}!</h1>
# hello.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/user/<name>")
def user(name):
return render_template("user.html", name=name)
if __name__ == "__main__":
app.run(debug=True)
<!-- templates/test.html -->
<p>mydict["key"]: {{ mydict["key"] }}</p>
<p>mylist[3]: {{ mylist[3] }}</p>
<p>mylist[myintvar]: {{ mylist[myintvar] }}</p>
<p>instance.method1(): {{ instance.method1() }}</p>
<p>instance.method2(): {{ instance.method2() }}</p>
<p>instance.method3(5): {{ instance.method3(5) }}</p>
<p>class.method2(): {{ class.method2() }}</p>
<p>class.method3(10): {{ class.method3(10) }}</p>
@app.route("/test")
def test():
mydict = {"key": "This is a secret"}
mylist = [1, 2, 3, 4]
myintvar = 0
class Myobj():
def method1(self):
return "I'm a instance method."
@staticmethod
def method2():
return "I'm a static method."
@classmethod
def method3(cls, value):
return "I'm a class method, get value {}".format(value)
context = {
"mydict": mydict,
"mylist": mylist,
"myintvar": myintvar,
"instance": Myobj(),
"class": Myobj
}
return render_template("test.html", **context)
<!-- templates/test.html -->
<p>mylist length: {{ len(mylist) }}</p>
<!-- templates/test.html -->
<p>mylist length: {{ mylist|length }}</p>
<!-- templates/user.html -->
<h1>Hello, {{ name|capitalize }}</h1>
<!-- template/test.html -->
{{ code }}
{{ code|safe }}
@app.route("/test")
def test():
code = "<h1>Hello</h1>"
return render_template("test.html", code=code)
@app.route("/vulnerable")
def vulnerable():
code = """<script>alert("I'm a hacker.")</script>"""
return render_template("test.html", code=code)
<!-- templates/user.html -->
<h1>Have tags: {{ name|title }}</h1>
<h1>No tags: {{ name|striptags|title }}</h1>
$
git clone https://github.com/win911/flask_class.git$
git checkout 202dc9<!-- templates/user.html -->
{% if name %}
<h1>Hello, {{ name|title }}!</h1>
{% else %}
<h1>Hello, Stranger!</h1>
{% endif %}
# hello.py
from flask import Flask, render_template
app = Flask(__name__)
registered_users = ["maomao", "alicia"]
@app.route("/user/<name>")
def user(name):
if name not in registered_users:
name = None
return render_template("user.html", name=name)
if __name__ == "__main__":
app.run(debug=True)
<!-- templates/users.html -->
<h1>User List</h1>
<ul>
{% for user in users %}
<li>{{ user|title }}</li>
{% endfor %}
</ul>
@app.route("/users")
def users():
return render_template("users.html", users=registered_users)
<!-- templates/users.html -->
{% macro render_user(user) %}
<li>{{ user|title }}</li>
{% endmacro %}
<h1>User List</h1>
<ul>
{% for user in users %}
{{ render_user(user) }}
{% endfor %}
</ul>
<!-- template/macros.html -->
{% macro render_user(user) %}
<li>{{ user|title }}</li>
{% endmacro %}
<!-- templates/users.html -->
{% import "macros.html" as macros %}
<h1>User List</h1>
<ul>
{% for user in users %}
{{ macros.render_user(user) }}
{% endfor %}
</ul>
<!-- templates/footer.html -->
<footer>
<p>footer © 2017</p>
</footer>
<!-- templates/users.html -->
{% import "macros.html" as macros %}
<h1>User List</h1>
<ul>
{% for user in users %}
{{ macros.render_user(user) }}
{% endfor %}
</ul>
{% include "footer.html" %}
<!-- templates/base.html -->
<html>
<head>
{% block head %}
<title>{% block title %}{% endblock %} - My Application </title>
{% endblock %}
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
<!-- templates/index.html -->
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style>
</style>
{% endblock %}
{% block body %}
<h1>Hello World!</h1>
{% endblock %}
@app.route("/")
def index():
return render_template("index.html")
$
git clone https://github.com/win911/flask_class.git$
git checkout ebf384from flask import Flask
app = Flask(__name__, template_folder="my_templates")
<!-- templates/user.html -->
{% extends "bootstrap/base.html" %}
{% block title %}Flasky{% endblock %}
{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle"
data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Flasky</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
</ul>
</div>
</div>
</div>
{% endblock %}
{% block content %}
<div class="container">
<div class="page-header">
<h1>Hello, {{ name }}!</h1>
</div>
</div>
{% endblock %}
# hello.py
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
#from flask.ext.bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap(app)
@app.route("/user/<name>")
def user(name):
return render_template("user.html", name=name)
if __name__ == "__main__":
app.run(debug=True)
{% block scripts %}
{{ super }}
<script type="text/javascript" src="my-script.js"></script>
{% endblock %}
<!-- templates/base.html -->
{% extends "bootstrap/base.html" %}
{% block title %}Flasky{% endblock %}
{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle"
data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Flasky</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
</ul>
</div>
</div>
</div>
{% endblock %}
{% block content %}
<div class="container">
{% block page_content %}{% endblock %}
</div>
{% endblock %}
<!-- templates/404.html -->
{% extends "base.html" %}
{% block title %}Flasky - Page Not Found{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Not Found</h1>
</div>
{% endblock %}
<!-- templates/500.html -->
{% extends "base.html" %}
{% block title %}Flasky - Error{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Internal Server Error</h1>
</div>
{% endblock %}
from flask import abort
@app.errorhandler(404)
def page_not_found(e):
return render_template("404.html"), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template("500.html"), 500
@app.route("/test")
def test():
abort(500)