My First Python Program

 1 # pip install flask. 导入import flask
 2 import traceback
 3 from flask import Flask, render_template, request
 4 import requests
 5 import datetime
 6 
 7 '''第一步:本文件,加密,创建一个flask'''
 8 #一。定义Flask
 9 # app = flask.Flask(__name__)
10 #找不到模板文件,故写绝对路径
11 # app = Flask(__name__,
12 #             template_folder='F:\\studdy\\python\\Python-master\\Python-master\\WeatherDemo\\flask_weather\\templates')
13 app = Flask(__name__,template_folder='./templates')
14 # 设置数据模板要 用个app
15 @app.template_filter('weeks')
16 def get_week_day(date):
17     # 替换
18     temp_date = datetime.datetime.strptime(date, '%Y-%m-%d')
19     week_day_dic = {
20         0: '周一',
21         1: '周二',
22         2: '周三',
23         3: '周四',
24         4: '周五',
25         5: '周六',
26         6: '周七',
27     }
28     day = temp_date.weekday()
29     return week_day_dic[day]
30 
31 
32 # 二。网页地址'''定义首页'''
33 @app.route('/')
34 def manage():
35     # 取到前端用户输入的城市,在链接后面加: ?c=上海,传参方式
36     city = request.args.get('c')
37     print(city)
38     if city:
39         url = 'http://apis.juhe.cn/simpleWeather/query?city={}&key=d3a1582e49bd9f3dc3a865cebc4353f8'.format(city)
40     else:
41         url = 'http://apis.juhe.cn/simpleWeather/query?city=%E4%B8%8A%E6%B5%B7&key=d3a1582e49bd9f3dc3a865cebc4353f8'
42     # 爬虫去请求数据
43     try:
44         response = requests.get(url).json()
45         print(response)
46         w_city = response['result']['city']
47         w_list = response['result']['future']
48         for i in w_list:
49             print('--' * 20)
50             print(i['date'])
51             print(i['temperature'])
52             print(i['weather'])
53             print(i['direct'])
54     except Exception as e:
55         print(traceback.print_exc())#打印错误信息
56         return "参数错误: %s" % e
57 
58     # 前后端数据交互,爬虫采集到的数据和前端模板产生关联
59     return render_template('weather.html', w_city=w_city, w_list=w_list)
60 
61 # 三。启动本地服务器,运行程序
62 #顶格,无空格写
63 if __name__ == '__main__':
64     app.run()

 

遇到的问题:jinja2.exceptions.TemplateNotFound

第一种情况:
  没有templates文件夹,因为默认情况下,Flask在程序文件夹中的templates子文件夹中寻找模板。
解决方案:
  在程序文件夹下边新建一个templates文件夹,将index.htmluser.html模板文件放进去。如下图所示:
存放文件相对路径:  

 

   

 链接:https://www.jianshu.com/p/8df0fbe4e64e
 
posted @ 2020-03-01 19:37  *人丑就该多读书*  阅读(251)  评论(0编辑  收藏  举报