看了一个比较简单的flask教程,Build a Complete Website Using Flask,一共20讲,快的话一两个小时可以看完吧。
这个教程讲的是做一个虚拟货币汇率的flask的小demo。
python代码文件index.py:
from flask import Flask
import requests
from flask import render_template
app = Flask(__name__)
@app.route('/')
def main():
url = "http://api.coinlayer.com/live?access_key=7b88c978bbe37fd6d7c9a393506df665&target=CNY"
response = requests.get(url)
response_json = response.json()
rates = response_json['rates']
target = response_json['target']
return render_template('rates.html', rates=rates, target=target)
if __name__ == "__main__":
app.debug = True
app.run(host='127.0.0.1', port=8000)
html静态模板文件放在templates文件夹里面,js、css文件需要放在static文件夹里面。rates.html代码是:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>虚拟币汇率</title>
<link rel="stylesheet" href="../static/bootstrap-5.3.2-dist/css/bootstrap.css">
</head>
<body>
<h3 class="text-center">比特币汇率 {{target}} </h3>
<div class="container">
<table class="table" style="text-align: left">
<thead>
<tr>
<th>虚拟币</th>
<th>兑人民币汇率</th>
</tr>
</thead>
<tbody>
{% for currency,rate in rates.items() %}
{% if rate >1000 %}
<tr class="table-danger">
<td>{{currency}}</td>
<td>{{rate}}</td>
</tr>
{% else %}
<tr class="">
<td>{{currency}}</td>
<td>{{rate}}</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
<script src="../static/bootstrap-5.3.2-dist/js/bootstrap.js"></script>
</body>
</html>
模板文件引用css、js的路径是../static/,感觉有点奇怪啊……
最后效果是:
项目demo源码:
andux_给我时间来成长-优快云博客 到我博客首页,找到Build a Complete Website Using Flask这个资源就点击,免费下载了。不知道为什么链接打不开,只有我登录后才能打开,好奇怪。
之前帮定不了资源,原来是资源正在审核,所以绑定不了,现在通过审核了,可以了。