Python安装了Flask以后无法使用run()函数
from flask import Flask

app=Flask(__name__)#导入和设置Flask

@app.route('/')#调用一种特殊类型的函数,称之为装饰器。

#在这里指明了想要页面从何处提供。斜杠表示想要它从URL的根目录下提供
def hello_world():
    return 'Hello World!'
#这个函数告诉Flask,想把哪些数据发送给那个页面

if(__name__=='__main__'):
    app.run()
#调用一个名为run()的Flask函数

上面是我的Python代码,下面是我的报错信息

Traceback (most recent call last):
  File "F:\大学\python\Flaskhello.py", line 13, in <module>
    app.run()
  File "F:\大学\python\lib\site-packages\flask\app.py", line 938, in run
    cli.show_server_banner(self.env, self.debug, self.name, False)
  File "F:\大学\python\lib\site-packages\flask\cli.py", line 629, in show_server_banner
    click.echo(message)
  File "F:\大学\python\lib\site-packages\click\utils.py", line 218, in echo
    file = _default_text_stdout()
  File "F:\大学\python\lib\site-packages\click\_compat.py", line 675, in func
    rv = wrapper_func()
  File "F:\大学\python\lib\site-packages\click\_compat.py", line 436, in get_text_stdout
    rv = _get_windows_console_stream(sys.stdout, encoding, errors)
  File "F:\大学\python\lib\site-packages\click\_winconsole.py", line 295, in _get_windows_console_stream
    func = _stream_factories.get(f.fileno())
io.UnsupportedOperation: fileno

这是我在DOS界面多次安装了Flask以后的语句

C:\Users\DELL>pip install flask
Requirement already satisfied: flask in f:\大学\python\lib\site-packages (1.0.2)
Requirement already satisfied: Werkzeug>=0.14 in f:\大学\python\lib\site-packages (from flask) (0.15.2)
Requirement already satisfied: click>=5.1 in f:\大学\python\lib\site-packages (from flask) (7.0)
Requirement already satisfied: itsdangerous>=0.24 in f:\大学\python\lib\site-packages (from flask) (1.1.0)
Requirement already satisfied: Jinja2>=2.10 in f:\大学\python\lib\site-packages (from flask) (2.10.1)
Requirement already satisfied: MarkupSafe>=0.23 in f:\大学\python\lib\site-packages (from Jinja2>=2.10->flask) (1.1.1)

1个回答

试一试在代码中添加环境变量运行,我linux系统里遇到了这个问题,修改后能正常运行

应该要查一下你python的位置,替换下地址

#! C:\Users\wjno1\AppData\Local\Programs\Python\Python37\python.exe

from flask import Flask

app=Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if(__name__=='__main__'):
    app.run()
weixin_44797433
风居住的街叨 回复weixin_43800490: 你python的地址是“F:\大学\python\python.exe” ??
大约一年之前 回复
weixin_44797433
风居住的街叨 回复weixin_43800490: 跟版本没关系,还有你为啥把python装到中文目录下,这样环境变量容易出现乱码,可能是这个原因,最好把它装到c盘下
大约一年之前 回复
weixin_43800490
weixin_43800490 你好,我那个包里有flask,是1.0.2的版本的,我的Python是3.7.3的,会是因为版本问题吗?
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
python的flask-web程序出错

1.python的flask-web程序不知道错在哪里,运行报错:The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.? from flask import Flask from flask import request from recommend import Recommend2 import json import glob import os.path configuration={ "DATA_PATH":"data", "PORT":8080 } #LOAD THE DATA JSON_LIST = [] paths = glob.glob( os.path.join(configuration["DATA_PATH"],"*.txt") ) for path in paths: fp = open(path,"r") JSON_LIST.append( json.load(fp) ) fp.close() def filter_json(json_list:list): """ 过滤每一条数据,用于测试集合 保留title :param json_list:电影数据 :return: 过滤后的结果 """ res = [] def func(inf:dict,json,key:str): """ 对于 A/B/C这样在同一个标签下有多个属性的进行过滤 :param inf: 字典 :param json: 需要过滤的单个json对象 :return: """ if key == "title": info["title"]=json["title"] return ks = j.get(key, "") k_l = ks.split("/") for k_i in range(len(k_l)): # print(ty_l[t_i]) info["%s%s" % (key,k_i + 1)] = k_l[k_i] for j in json_list: info = dict() info["title"] = j.get("title") for k in j : if k not in ["comment_list","date","runtime"]: func(info,j,k) res.append(info) return res # print(filter_json(JSON_LIST)) app = Flask(__name__) system = Recommend2(7*24*3600) @app.route("/recommend/get",methods=['GET']) def get(): """ 获取推荐结果 :return: 推荐结果 """ test_set=filter_json(JSON_LIST) res = system.result(test_set,5) def _filter(j): """ 将comment_list弄成字符串 """ nj = j.copy() nj["comment_list"] = "|".join(nj["comment_list"]) return nj return json.dumps( [ _filter(JSON_LIST[i]) for i in res] ) @app.route("/recommend/put",methods=["GET"]) def put(): """ 提取数据再学习 :return: """ movie_name = request.args.get("moviename",None) comment = request.args.get("comment",None) if (not movie_name) or (not comment): return json.dumps({"sta":"failed"}) print(movie_name) if comment == "good": temp = [ filter_json([x])[0] for x in JSON_LIST if x.get("title","") == movie_name ] system.learn(temp[0]) return json.dumps({"sta":"succeed"}) @app.route("/recommend/info") def get_info(): return json.dumps(system.getLike()) if __name__ == "__main__": app.run(port=configuration["PORT"],debug=True)

Flask主函数无法执行问题。

初学Python的Flask框架,版本python3.6,使用的是pycharm,代码如下。 ``` # -*- coding:utf-8 -*- from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) class Config(): # sqlalchemy配置参数 SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:toor@localhost:3306/author_book_py04' # 设置sqlalchemy自动跟踪数据库 SQLALCHEMY_TRACK_MODIFICATIONS = True app.config.from_object(Config) db = SQLAlchemy(app) # 定义数据库的模型 class Author(db.Model): """作者""" __tablename__ = 'tbl_authors' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32), unique=True) class Book(db.Model): """书籍""" __tablename__ = 'tbl_books' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) author_id = db.Column(db.Integer, db.ForeignKey("tbl_authors.id")) if __name__ == '__main__': db.drop_all() db.create_all() au_xi = Author(name='我吃西红柿') au_qian = Author(name='萧潜') au_san = Author(name='唐家三少') db.session.add_all([au_xi, au_qian, au_san]) db.session.commit() bk_xi = Book(name='吞噬星空', author_id=au_xi.id) bk_xi2 = Book(name='寸芒', author_id=au_qian) bk_qian = Book(name='飘渺之旅', author_id=au_qian) bk_san = Book(name='冰火魔厨', author_id=au_san) db.session.add_all([bk_xi, bk_xi2, bk_qian, bk_san]) db.session.commit() app.run() ``` 主要是想通过Flask链接MySQL数据库进行数据表的创建和内容的写入。 代码不会报错,但是并不会创建新的数据表,也不会赋值,就是主函数没有被执行的样子。如果我把主函数去掉,如下: ``` # -*- coding:utf-8 -*- from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) class Config(): # sqlalchemy配置参数 SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:toor@localhost:3306/author_book_py04' # 设置sqlalchemy自动跟踪数据库 SQLALCHEMY_TRACK_MODIFICATIONS = True app.config.from_object(Config) db = SQLAlchemy(app) # 定义数据库的模型 class Author(db.Model): """作者""" __tablename__ = 'tbl_authors' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32), unique=True) class Book(db.Model): """书籍""" __tablename__ = 'tbl_books' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) author_id = db.Column(db.Integer, db.ForeignKey("tbl_authors.id")) db.drop_all() db.create_all() au_xi = Author(name='我吃西红柿') au_qian = Author(name='萧潜') au_san = Author(name='唐家三少') db.session.add_all([au_xi, au_qian, au_san]) db.session.commit() bk_xi = Book(name='吞噬星空', author_id=au_xi.id) bk_xi2 = Book(name='寸芒', author_id=au_qian) bk_qian = Book(name='飘渺之旅', author_id=au_qian) bk_san = Book(name='冰火魔厨', author_id=au_san) db.session.add_all([bk_xi, bk_xi2, bk_qian, bk_san]) db.session.commit() app.run() ``` 这样的话就没有任何问题,数据表也可以正常创建,数据内容也可以添加进去。 这会图片无法上传,我试试可以在评论里边上传图片不有知道的大佬说一下。

python语言用flask做二维码生成,二维码生成失败,这是怎么回事?

下面是代码文件,webapp.py qrc.py url.html 三个文件 求前辈们指教,运行时出现这个问题 ![图片说明](https://img-ask.csdn.net/upload/201704/18/1492510445_532709.png) #webapp.py #coding=utf-8 from flask import Flask from flask import render_template from flask import redirect from flask import url_for from flask import request import qrc app = Flask(__name__) @app.route('/') #设置装饰器 路由 '/'表示路径 def index(): #把函数加载到装饰器里 显示首页 return redirect(url_for('url')) #这里的url是函数名 主页返回函数所在的route的路径 @app.route('/url',methods=['GET','POST']) def url():#默认请求方式为GET #print(request.method) #request当中包含所有的请求数据和头信息 if request.method =='GET': return render_template('url.html') url = request.form['url'] imgurl = qrc.url(url) return imgurl if __name__ == '__main__': app.run(debug=True) #启动时启动debug调试模式,调试的时候建议启动 #qrc.py # coding=utf-8 __author__ = 'Administrator' import qrcode # qrcode是专门生成二维码的库 from PIL import Image def url(url): img = qrcode.make(url) # 已经生成二维码图片对象 img.save('static/qrimg/1.png',"png") # 保存二维码图片 return 'static/qrimg/1.png' #url.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>通过url生成二维码</title> </head> <body> <form action="/url" method="post"> url:<input type="text" name="url" value="http://"/> <input type="submit" value="生成二维码"> </form> </body> </html> ``` ```

python flask在主app.py文件中定义了一个工厂函数create_app(),并且创建列一个app实例,为什么还是会报Failed to find application in module "app"的错误。

python flask在主app.py文件中定义了一个工厂函数create_app(),并且创建列一个app实例,为什么还是会报Failed to find application in module "app"的错误。 工厂函数以及main方法 ``` # --app.py def create_app(): app = Flask(__name__) app.config.from_object(config) return app if __name__ == '__main__': app = create_app() app.run() ``` 为什么还是报错: Error: Failed to find application in module "app". Are you sure it contains a Flask application? Maybe you wrapped it in a WSGI middleware or you are using a factory function.

flask 定义的路由找不到了,请问该如何定义flask路由

![图片说明](https://img-ask.csdn.net/upload/201511/10/1447162707_359837.png) 上面的图是这个项目的目录结构,和run.py 的代码,其余代码如下: app文件夹中的__init__.py: ``` app --init from flask import Flask, render_template, json, request from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('config') @app.route('/') def index(): return render_template('home.html') # return "hello" @app.route('/signin', methods=['GET', 'POST']) def signin(): return 'ok' ``` 下面的是home.html的代码 ``` <input type="text" id="name" placeholder="Username"> <input type="text" id="password" class="inbox" placeholder="password"> <div style="text-align:center"> <input type="button" id="btn_up_submit" class="btn btn-primary" value="sign up" onclick="upSubmit()"> <input type="button" id="btn_up_cancel" class="btn btn-success" value="cancel" onclick="upCancel()"> </div> <script> function upSubmit() { var name = $("#name").val(); var password = $("#password").val(); mydata = { 'name':name, 'password':password }; $.getJSON('/signin') # 我不知道在js里如何可以寻找路由,在网上看到了有这个代码就写了试试, } <script> ``` 有两个问题: 问题一:运行该程序后可以正常显示home.htm页面,但是为什么 我点击button按钮触发upSubmit找不到/signin这个路由呢,是不是需要在哪个地方设置? 问题二:如果不用getJSON这个方法也可以,请老师推荐一个其他方法,在js里面写然后可以找到路由并且可以传值,因为后期肯定还要传值。 万分感谢

Flask form表单返回多个Immutable Dict的问题

我用form表单进行html数据的提交,然后Flask这边用request.form进行读取。我只想要第二个dict里的内容,我好提取key为name的值,但是第一个怎么把它去掉呢或者不影响我程序的执行。现在这个src是这两个字典,而不是一个 ![图片说明](https://img-ask.csdn.net/upload/202004/18/1587194476_906167.png) 我的html代码如下: ``` <form action="{{url_for('handleLocal')}}" method="post"> <input class="uploadImg file1" type="file" name="file1" id="EmployeePicture" hidden accept="image/*" onchange="showImgToView('EmployeePicture')"/> <button class="button1" id="submitLocalFile" type="submit" onclick="transmit()" ><span>预测</span></button> ``` 这里的input是用来上传图片的,我后端并不怎么需要它。 我需要的是图片的src,所以我写了个在button提交的function ``` function transmit() { var transmit_content=$('#change_Image')[0].src; $.ajax({ url: "{{url_for('handleLocal')}}", data: {name: transmit_content}, type: "POST", //dataType: "json", }); } ``` 然后是Flask部分代码: ``` @app.route('/handleLocal',methods=['POST']) def handleLocal(): ** src=request.form.get('name')** data=src[23:-1] img_data=base64.b64decode(data+"=") ``` 问题就出在 handleLocal函数中 src=request.form会返回两个字典,我如果get的话一个结果是none,一个结果是我想要的src属性 请教大家如何解决这个问题

flask 新手遇到KEYERROR问题

# KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS' sql代码 ``` from flask import Flask from flask_sqlalchemy import SQLAlchemy import os basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///'+os.path.join(basedir,'data.sqlite') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] =True db = SQLAlchemy(app) class Role(db.Model): __tablename__ = 'roles'#__tablename__ 定义在数据库中使用的表名 id = db.Column(db.Integer, primary_key=True)#primary_key如果设为 True ,这列就是表的主键.如果没有定义 __tablename__ ,SQLAlchemy 会使用一个默认名字 name = db.Column(db.String(64), unique=True) users = db.relationship('User', backref='role') def __repr__(self): return '<Role % r>' % self.name class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, index=True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) def __repr__(self): return '<User % r>' % self.username ```主程序代码 ``` from flask import Flask,render_template,url_for,session,redirect,flash from flask_bootstrap import Bootstrap from flask.ext.moment import Moment import os from flask_sqlalchemy import SQLAlchemy from flask.ext .wtf import Form from wtforms import StringField,SubmitField #字段类型类导入 字符串,提交 from wtforms.validators import DataRequired #从表单验证 导入 请求 from datetime import datetime from sql import db,User,Role,app class NameForm(Form): name = StringField('你的名字 ?',validators=[DataRequired()]) #DataRequired()[验证函数]表示数据示为必须非空 submit = SubmitField('提交') app = Flask(__name__) app.config['SECRET_KEY'] ='hard to guess string' bootstrap = Bootstrap(app) monent = Moment(app) @app.route('/',methods=['GET','POST']) #app后面的metheds参数告诉Flask 在URL映射中吧视图函数注册为Get Post请求的处理程序.如果没有metheds #参数,就只把视图函数注册为GET请求的处理程序 def index(): form = NameForm() if form.validate_on_submit():#如果数据能被所有验证函数接收(上面的)返回True 否则False user = User.query.filter_by(username = form .name.data).first() if user is None: user = User(username = form.name.data ) db.session.add(user) session['known'] =False else: session['known']= True session['name'] = form.name.data form .name.data='' return redirect(url_for('index')) return render_template('user.html',form = form ,name=session.get('name'),known = session.get('known',False)) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'),404 if __name__ == '__main__': app.run(debug=True) ```一提交表单就错误 图片![![图片说明](https://img-ask.csdn.net/upload/201801/12/1515731831_287746.png)图片说明](https://img-ask.csdn.net/upload/201801/12/1515731822_970460.png)

uWSGI uwsgi uwsgi.ini 启动报错怎么办

``` [root@VM_0_15_centos ~]# cd /www [root@VM_0_15_centos www]# uwsgi uwsgi.ini [uWSGI] getting INI configuration from uwsgi.ini *** Starting uWSGI 2.0.18 (64bit) on [Sun Aug 11 20:18:39 2019] *** compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-36) on 11 August 2019 11:49:00 os: Linux-3.10.0-862.el7.x86_64 #1 SMP Fri Apr 20 16:44:24 UTC 2018 nodename: VM_0_15_centos machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 1 current working directory: /www detected binary path: /usr/local/bin/uwsgi setgid() to 1000 setuid() to 1000 chdir() to /www *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 3882 your memory page size is 4096 bytes detected max file descriptor number: 100001 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to TCP address 127.0.0.1:9000 fd 3 Python version: 3.7.0 (default, Aug 11 2019, 19:03:29) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] Python main interpreter initialized at 0x1ef25f0 python threads support enabled your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 333504 bytes (325 KB) for 8 cores *** Operational MODE: preforking+threaded *** added /www/ to pythonpath. ModuleNotFoundError: No module named 'www' unable to load app 0 (mountpoint='') (callable not found or import error) WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x1ef25f0 pid: 26222 (default app) *** uWSGI is running in multiple interpreter mode *** spawned uWSGI worker 1 (pid: 26222, cores: 2) spawned uWSGI worker 2 (pid: 26223, cores: 2) spawned uWSGI worker 3 (pid: 26224, cores: 2) spawned uWSGI worker 4 (pid: 26225, cores: 2) ``` **启动报错已经解决了一个,但是其他的实在没办法 大神,怎么解决 之前没这个问题,出现之后不管怎么重新装系统都解决不了** 以下是配置文件 ``` [uwsgi] uid = www gid = www socket = 127.0.0.1:9000 chdir = /www module=www.wsgi wsgi-file = /www/hello.py callable = app processes = 4 threads = 2 pythonpath = /www ``` 十分感激,实在是找不到方法了,网络上的都找了

python3 怎样用threading多线程处理同一数据

怎样用threading多线程处理同一数据打印? 函数a的内容是输出1-100 想用threading方法,开5条线程同时完成1-100的输出 注意:假如线程1输出的是1,其他线程就只能输出2 不能重复输出1...以此类推 import threading lock = threading.Lock() def a(): for i in range(1,100): print (i,threading.currentThread()) for i in range(5): th=threading.Thread(target=a,args=()) th.start()

websocket连接失败,进不了函数on_open和on_message

websocket连接大概如下,但是运行程序时,函数on_open、on_message都没有被执行,完全没有进入?想问下是什么情况?感谢大佬告知!!!急!!! ``` def SendWebSocket: class __init__(self, file,url): self.file = self.rul = def on_message(self, ws, message): print('message') def on_open(self,ws): prnit('open') def on_error(self,ws,error): print('error') def main(self): ws = websocket.WebSocketApp(self.url, on_message=self.on_message, on_error=self.on_error) ws.on_open = self.on_open ws.run_forever() if __name__ == '__main__': sws = SendWebSocket(file, url) sws.main() ```

利用ajax动态的提取mysql中的数据,并且在前端页面中展示出来

代码如下: 前端html: ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <!--<script type="text/javascript" src="jquery.js"></script>--> <script type="text/javascript" src="http://echarts.baidu.com/gallery/vendors/echarts/echarts.min.js"></script> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <body> <div id="main" style="width: 600px;height:400px;"></div> </body> </html> <script> var app = { xvalue: [], yvalue: [], z:[], }; // 发送ajax请求,从后台获取json数据 $(document).ready(function () { getData(); console.log(app.value1); console.log(app.timepoint) console.log(app.predictvalue1) }); function getData() { $.ajax({ url: '/test', data: {}, type: 'POST', async: false, dataType: 'json', success: function (data) { app.value1 = data.value1; app.predictvalue1=data.predictvalue1; value1 = app.value1; predictvalue1=app.predictvalue1; function trueData(i) { now = new Date(+now + oneDay); value = value1[i]; return { name: now.toString(), value: [ [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'), Math.round(value) ] } } function predictData(i) { now1 = new Date(+now1 + oneDay); predictvalue = predictvalue1[i]; return { name: now1.toString(), value: [ [now1.getFullYear(), now1.getMonth() + 1, now1.getDate()].join('/'), Math.round(predictvalue) ] } } var data = []; var predictdata=[]; var now = +new Date(1997, 9, 3); var now1 = +new Date(1997, 9, 4); var oneDay = 24 * 3600 * 1000; for (var i = 0; i < value1.length; i++) { data.push(trueData(i)); } for (var i = 0; i < predictvalue1.length; i++) { predictdata.push(predictData(i)); } // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); option = { title: { text: '动态数据 + 时间坐标轴' }, tooltip: { trigger: 'axis', formatter: function (params) { params = params[0]; var date = new Date(params.name); return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' : ' + params.value[1]; }, axisPointer: { animation: false } }, xAxis: { type: 'time', splitLine: { show: false } }, yAxis: { type: 'value', boundaryGap: [0, '100%'], splitLine: { show: false } }, series: [{ name: '真实数据', type: 'line', showSymbol: false, hoverAnimation: false, data: [], markLine: { itemStyle: { normal: { borderWidth: 1, lineStyle: { type: "dash", color: 'red', width: 2 }, show: true, color: '#4c5336' } }, data: [{ yAxis: 900 }] } }, { name: '预测数据', type: 'line', showSymbol: false, hoverAnimation: false, data: [], markLine: { itemStyle: { normal: { borderWidth: 1, lineStyle: { type: "dash", color: 'blue', width: 2 }, show: true, color: '#4c5336' } }, data: [{ yAxis: 900 }] } }] }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); setInterval(function () { for (var i = 0; i < 1; i++) { data.shift(); data.push(trueData(i)); } for (var i = 0; i < 1; i++) { predictdata.shift(); predictdata.push(predictData(i)); } myChart.setOption({ series: [{ data: data }, { data: predictdata }] }); }, 1000); } }) } </script> </body> </html> ``` 后端py,用的是flask框架: ``` import MySQLdb from flask import Flask, render_template, url_for import pymysql import pandas as pd import numpy as np from pandas import read_csv import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from keras.models import Sequential from keras.layers import LSTM, Dense, Activation,Dropout import json import operator from functools import reduce import math import tensorflow as tf from keras import initializers import time # 生成Flask实例 app = Flask(__name__) @app.route("/") def hello(): return render_template('new_file.html') # /test路由 接收前端的Ajax请求 @app.route('/test', methods=['POST']) def my_echart(): # 连接数据库 conn = MySQLdb.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='test', charset='utf8') cur = conn.cursor() sql = 'SELECT timepoint,value1 from timeseries' cur.execute(sql) u = cur.fetchall() timepoint = [] value1 = [] for data in u: value1.append(data[1]) timepoint.append(data[0]) print(value1) # 转换成json格式 jsonData = {} jsonData['value1'] = value1 jsonData['timepoint']=timepoint # json.dumps()用于将dict类型的数据转换成str,因为如果直接将dict类型的数据写入json会报错,因此将数据写入时需要用到此函数 j = json.dumps(jsonData) cur.close() conn.close() # 在浏览器上渲染my_template.html模板(为了查看输出数据) return (j) if __name__ == '__main__': app.run(debug=True,port='5000') ``` 返回的数据是从mysql中读取的,现在我想用ajax的方法定时请求数据库的下一个数据到达前台,并且刷新页面显示出来,应该怎么修改代码? 数据库如下: ![图片说明](https://img-ask.csdn.net/upload/201905/24/1558685991_221903.jpg)

关于python中if __name__ == '__main__'的问题

初学python,想请教一下大神,在python中 ``` if __name__ == '__main__': ``` 这行代码的意义是什么呢,在C语言中main函数是程序执行的入口,这行代码是否可以类似地理解?

keras 并发load_model报错

我通过web代码实时加载模型进行预测,但报如下错误 Traceback (most recent call last): File "/root/anaconda3/lib/python3.6/site-packages/flask/app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "/root/anaconda3/lib/python3.6/site-packages/flask/app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "/root/anaconda3/lib/python3.6/site-packages/flask/app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "/root/anaconda3/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise raise value File "/root/anaconda3/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/root/anaconda3/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/root/anaconda3/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/root/anaconda3/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise raise value File "/root/anaconda3/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/root/anaconda3/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/root/anaconda3/code/App.py", line 41, in predict model=load_model(root_path+model_name) File "/root/anaconda3/lib/python3.6/site-packages/keras/models.py", line 249, in load_model topology.load_weights_from_hdf5_group(f['model_weights'], model.layers) File "/root/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py", line 3008, in load_weights_from_hdf5_group K.batch_set_value(weight_value_tuples) File "/root/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 2189, in batch_set_value get_session().run(assign_ops, feed_dict=feed_dict) File "/root/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 895, in run run_metadata_ptr) File "/root/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1071, in _run + e.args[0]) TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(1, 16), dtype=float32) is not an element of this graph.

使用Docker创建镜像时,requests.get超时的问题

我们使用Docker创建多个ip结点,进行实验时,有一步调用了requests.get函数,结果发现超时。相关程序如下(语言为python): ``` response = requests.get(f'http://{node}/transactions/received',timeout = 1) ``` 异常为:requests.exceptions.ConnectTimeout 我们创建端口使用的是flask包,该网址的定义如下: ``` @app.route('/transactions/received', methods=['GET']) def received_transaction(): response = {'received_transaction': blockchain.received_transaction,} return jsonify(response), 201 ``` 由于不用Docker,直接运行程序创建结点时执行顺利。因此推断程序无误,而是Docker配置上出现了问题。 Docker创建网络的命令大致如下: docker run --rm -p $1001:$5000 --net blockchain1 --name node1 --ip $1.0.0.10 cjkdblockchain 不知道为什么requests.get会超时,请大家指教,谢谢!

flask+mysql实现的web应用,在注册页面点击注册后提示 Instance '<User at 0x5486a10>' has been deleted?

##问题描述 从github(https://github.com/num10/transfile)上下载的一个用flask+mysql实现的转pdf成word的web应用,其中 涉及到新用户的注册: ![图片说明](https://img-ask.csdn.net/upload/201911/07/1573098094_252858.png) 可是在注册页面填完信息点击注册后前端报错如下: ![图片说明](https://img-ask.csdn.net/upload/201911/07/1573098203_905955.png) ``` sqlalchemy.orm.exc.ObjectDeletedError: Instance '<User at 0x58072f0>' has been deleted, or its row is otherwise not present. ``` 根据traceback的信息,定位到出错的位置应该是下图中的models.py和views.py文件 ![图片说明](https://img-ask.csdn.net/upload/201911/07/1573100399_404211.jpg) 后台关于这两个文件的报错信息为: ```ruby File "C:\Users\26808\transfile-master\app\auth\views.py", line 68, in register token = user.generate_confirmation_token() File "C:\Users\26808\transfile-master\app\models.py", line 142, in generate_confirmation_token return s.dumps({'confirm': self.id}).decode('utf-8') ``` 对应文件中: views.py: ```ruby @auth.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() send_email(user.email, '认证您的账户', 'auth/email/confirm', user=user, token=token) flash('认证信息已发送至您的邮箱') return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form) ``` models.py: ``` def generate_confirmation_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}).decode('utf-8') ``` ##补充 1.按照requirements文件的要求,flask都安装了正确的包 2.正如register函数中所写的那样,点击注册后用户信息会被加入mysql数据库中但是会被重复加入,即多次运行每次都出错,并且相同的用户被反复加入mysql数据库中 3.网上大多数都是通过app.run()来启动文件的,但是这个项目里面先要设置 ```set FLASK_APP = manage.py``` 在```flask run```才能运行 能解释一下为什么吗? manage.py代码如下: ```ruby #!/usr/bin/ python # -*- coding: UTF-8 -*- import os COV = None if os.environ.get('FLASK_COVERAGE'): import coverage COV = coverage.coverage(branch=True, include='app/*') COV.start() import sys import click from flask_migrate import Migrate,upgrade from app import create_app, db from app.models import User, Follow, Role, Permission, Post, Comment from flask_uploads import configure_uploads from app.auth.forms import pdfs,photos,words app = create_app(os.getenv('FLASK_CONFIG') or 'default') migrate = Migrate(app, db) configure_uploads(app, pdfs) configure_uploads(app, photos) configure_uploads(app, words) @app.shell_context_processor def make_shell_context(): return dict(db=db, User=User, Follow=Follow, Role=Role, Permission=Permission, Post=Post, Comment=Comment) @app.cli.command() @click.option('--coverage/--no-coverage', default=False, help='Run tests under code coverage.') def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import subprocess os.environ['FLASK_COVERAGE'] = '1' sys.exit(subprocess.call(sys.argv)) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase() @app.cli.command() @click.option('--length', default=25, help='Number of functions to include in the profiler report.') @click.option('--profile-dir', default=None, help='Directory where profiler data files are saved.') def profile(length=25, profile_dir=None): """Start the application under the code profiler.""" from werkzeug.contrib.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length], profile_dir=profile_dir) app.run(debug=False) @app.cli.command() def deploy(): """Run deployment tasks.""" # migrate database to latest revision upgrade() # create or update user roles Role.insert_roles() # ensure all users are following themselves User.add_self_follows() if __name__ == '__main__': deploy() ``` 数据模型models.py: ``` #!/usr/bin/ python # -*- coding: UTF-8 -*- from datetime import datetime import hashlib from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from markdown import markdown import bleach from flask import current_app, request,url_for from flask_login import UserMixin, AnonymousUserMixin from . import db, login_manager class Permission: FOLLOW = 1 COMMENT = 2 WRITE = 4 MODERATE = 8 ADMIN = 16 class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) default = db.Column(db.Boolean, default=False, index=True) permissions = db.Column(db.Integer) users = db.relationship('User', backref='role', lazy='dynamic') def __init__(self, **kwargs): super(Role, self).__init__(**kwargs) if self.permissions is None: self.permissions = 0 @staticmethod def insert_roles(): roles = { 'User': [Permission.FOLLOW, Permission.COMMENT, Permission.WRITE], 'Moderator': [Permission.FOLLOW, Permission.COMMENT, Permission.WRITE, Permission.MODERATE], 'Administrator': [Permission.FOLLOW, Permission.COMMENT, Permission.WRITE, Permission.MODERATE, Permission.ADMIN], } default_role = 'User' for r in roles: role = Role.query.filter_by(name=r).first() if role is None: role = Role(name=r) role.reset_permissions() for perm in roles[r]: role.add_permission(perm) role.default = (role.name == default_role) db.session.add(role) db.session.commit() def add_permission(self, perm): if not self.has_permission(perm): self.permissions += perm def remove_permission(self, perm): if self.has_permission(perm): self.permissions -= perm def reset_permissions(self): self.permissions = 0 def has_permission(self, perm): return self.permissions & perm == perm def __repr__(self): return '<Role %r>' % self.name class Follow(db.Model): __tablename__ = 'follows' follower_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) followed_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) timestamp = db.Column(db.DateTime, default=datetime.utcnow) class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), unique=True, index=True) username = db.Column(db.String(64), unique=True, index=True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) password_hash = db.Column(db.String(128)) confirmed = db.Column(db.Boolean, default=False) name = db.Column(db.String(64)) location = db.Column(db.String(64)) about_me = db.Column(db.Text()) member_since = db.Column(db.DateTime(), default=datetime.utcnow) last_seen = db.Column(db.DateTime(), default=datetime.utcnow) avatar_hash = db.Column(db.String(32)) posts = db.relationship('Post', backref='author', lazy='dynamic') followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') comments = db.relationship('Comment', backref='author', lazy='dynamic') @staticmethod def add_self_follows(): for user in User.query.all(): if not user.is_following(user): user.follow(user) db.session.add(user) db.session.commit() def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.role is None: if self.email == current_app.config['FLASKY_ADMIN']: self.role = Role.query.filter_by(name='Administrator').first() if self.role is None: self.role = Role.query.filter_by(default=True).first() if self.email is not None and self.avatar_hash is None: self.avatar_hash = self.gravatar_hash() self.follow(self) @property def password(self): raise AttributeError('password is not a readable attribute') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password) def generate_confirmation_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}).decode('utf-8') def confirm(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token.encode('utf-8')) except: return False if data.get('confirm') != self.id: return False self.confirmed = True db.session.add(self) return True def generate_reset_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id}).decode('utf-8') @staticmethod def reset_password(token, new_password): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token.encode('utf-8')) except: return False user = User.query.get(data.get('reset')) if user is None: return False user.password = new_password db.session.add(user) return True def can(self, perm): return self.role is not None and self.role.has_permission(perm) def is_administrator(self): return self.can(Permission.ADMIN) def ping(self): self.last_seen = datetime.utcnow() db.session.add(self) def gravatar_hash(self): return hashlib.md5(self.email.lower().encode('utf-8')).hexdigest() def gravatar(self, size=100, default='identicon', rating='g'): url = 'https://secure.gravatar.com/avatar' hash = self.avatar_hash or self.gravatar_hash() return '{url}/{hash}?s={size}&d={default}&r={rating}'.format( url=url, hash=hash, size=size, default=default, rating=rating) def follow(self, user): if not self.is_following(user): f = Follow(follower=self, followed=user) db.session.add(f) def unfollow(self, user): f = self.followed.filter_by(followed_id=user.id).first() if f: db.session.delete(f) def is_following(self, user): if user.id is None: return False return self.followed.filter_by( followed_id=user.id).first() is not None def is_followed_by(self, user): if user.id is None: return False return self.followers.filter_by( follower_id=user.id).first() is not None @property def followed_posts(self): return Post.query.join(Follow, Follow.followed_id == Post.author_id)\ .filter(Follow.follower_id == self.id) def to_json(self): json_user = { 'url': url_for('api.get_user', id=self.id), 'username': self.username, 'member_since': self.member_since, 'last_seen': self.last_seen, 'posts_url': url_for('api.get_user_posts', id=self.id), 'followed_posts_url': url_for('api.get_user_followed_posts', id=self.id), 'post_count': self.posts.count() } return json_user def generate_auth_token(self, expiration): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}).decode('utf-8') @staticmethod def verify_auth_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return None return User.query.get(data['id']) def __repr__(self): return '<User %r>' % self.username class AnonymousUser(AnonymousUserMixin): def can(self, permissions): return False def is_administrator(self): return False login_manager.anonymous_user = AnonymousUser @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) body = db.Column(db.Text) body_html = db.Column(db.Text) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) comments = db.relationship('Comment', backref='post', lazy='dynamic') @staticmethod def on_changed_body(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul', 'h1', 'h2', 'h3', 'p'] target.body_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True)) def to_json(self): json_post = { 'url': url_for('api.get_post', id=self.id), 'body': self.body, 'body_html': self.body_html, 'timestamp': self.timestamp, 'author_url': url_for('api.get_user', id=self.author_id), 'comments_url': url_for('api.get_post_comments', id=self.id), 'comment_count': self.comments.count() } return json_post @staticmethod def from_json(json_post): body = json_post.get('body') if body is None or body == '': raise ValidationError('post does not have a body') return Post(body=body) db.event.listen(Post.body, 'set', Post.on_changed_body) class Comment(db.Model): __tablename__ = 'comments' id = db.Column(db.Integer, primary_key=True) body = db.Column(db.Text) body_html = db.Column(db.Text) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) disabled = db.Column(db.Boolean) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) post_id = db.Column(db.Integer, db.ForeignKey('posts.id')) @staticmethod def on_changed_body(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'code', 'em', 'i', 'strong'] target.body_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True)) db.event.listen(Comment.body, 'set', Comment.on_changed_body) ```

python 'if __name__ == "__main__":' 错误,直接执行测试(Terminal 运行正常)

main.py中的测试函数 import os.path as osp import pickle import model import weights import test def get_tf_implementation(weights_path, all_layer_outs=False): print("Making Structure") tf_model = model.make_deng_tf_test(verbose=True, all_layer_outs=all_layer_outs) print("Loading Weights") tf_model = weights.load_weights(tf_model, weights_path, verbose=True) return tf_model def get_test_data(cache_file): print("Loading Test Data") if osp.exists(cache_file): with open(cache_file, 'rb') as fid: roidb = pickle.load(fid) print('data is loaded from {}'.format(cache_file)) print(f"Number of Images to test: {len(roidb)}") return roidb def get_weighted_tf_implementation(weights_path, all_layer_outs=False): tf_model = get_tf_implementation(weights_path, all_layer_outs) model.show_model_info(tf_model) return tf_model def test_tf_implementation(cache_file, weights_path, all_layer_outs=False): # Get Weighted Model tf_model = get_weighted_tf_implementation(weights_path, all_layer_outs) # Load Cached Test Data roidb = get_test_data(cache_file) # Test Network results = test.test_net(tf_model, roidb) return results if __name__ == "__main__ 代码段: if __name__ == "__main__": results = test_tf_implementation(cache_file="roidb_test_19_smol.pkl", weights_path="rgbd_det_iter_40000.h5") Terminal运行一切正常,给cache-file和weights-path赋值,然后正常执行test_tf_implementation. 不知道问题出在哪里 错误提示: Using TensorFlow backend. EE ====================================================================== ERROR: main.get_test_data ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/xijiejiao/anaconda2/envs/python3/lib/python3.6/site-packages/nose/case.py", line 197, in runTest self.test(*self.arg) TypeError: get_test_data() missing 1 required positional argument: 'cache_file' -------------------- >> begin captured logging << -------------------- tensorflow: Level 1: Registering FakeQuantWithMinMaxArgs (<function _FakeQuantWithMinMaxArgsGradient at 0x1314c2598>) in gradient. tensorflow: Level 1: Registering FakeQuantWithMinMaxVars (<function _FakeQuantWithMinMaxVarsGradient at 0x1314c27b8>) in gradient. ``` ``` Error Traceback (most recent call last): File "/Users/xijiejiao/anaconda2/envs/python3/lib/python3.6/unittest/case.py", line 59, in testPartExecutor yield File "/Users/xijiejiao/anaconda2/envs/python3/lib/python3.6/unittest/case.py", line 605, in run testMethod() File "/Users/xijiejiao/anaconda2/envs/python3/lib/python3.6/site-packages/nose/case.py", line 197, in runTest self.test(*self.arg) Exception: get_test_data() missing 1 required positional argument: 'cache_file' -------------------- >> begin captured logging << -------------------- tensorflow: Level 1: Registering FakeQuantWithMinMaxArgs (<function _FakeQuantWithMinMaxArgsGradient at 0x1314c2598>) in gradient. tensorflow: Level 1: Registering FakeQuantWithMinMaxVars (<function _FakeQuantWithMinMaxVarsGradient at 0x1314c27b8>) in gradient. ``` ``` Error Traceback (most recent call last): File "/Users/xijiejiao/anaconda2/envs/python3/lib/python3.6/unittest/case.py", line 59, in testPartExecutor yield File "/Users/xijiejiao/anaconda2/envs/python3/lib/python3.6/unittest/case.py", line 605, in run testMethod() File "/Users/xijiejiao/anaconda2/envs/python3/lib/python3.6/site-packages/nose/case.py", line 197, in runTest self.test(*self.arg) TypeError: test_tf_implementation() missing 2 required positional arguments: 'cache_file' and 'weights_path' tensorflow: Level 1: Registering NcclAllReduce (<function _all_sum_grad at 0x131d62620>) in gradient. tensorflow: Level 1: Registering NcclReduce (<function _reduce_sum_grad at 0x131d628c8>) in gradient. tensorflow: Level 1: Registering NcclBroadcast (<function _broadcast_grad at 0x131d629d8>) in gradient. ``` ``` ====================================================================== ERROR: main.test_tf_implementation ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/xijiejiao/anaconda2/envs/python3/lib/python3.6/site-packages/nose/case.py", line 197, in runTest self.test(*self.arg) TypeError: test_tf_implementation() missing 2 required positional arguments: 'cache_file' and 'weights_path' ---------------------------------------------------------------------- Ran 2 tests in 0.020s FAILED (errors=2) Process finished with exit code 1 Assertion failed Assertion failed Assertion failed Assertion failed

smtplib断开连接:连接意外关闭?

Python—爬虫之实操项目:将爬取的数据定时发送邮件‘ import requests #导入requests库 import smtplib #发送邮件使用 import schedule #定时发送 import time #时间模块 from bs4 import BeautifulSoup #导入BeautifulSoup from email.mime.text import MIMEText #构建邮件内容 from email.header import Header #构建邮件头 #输入隐私信息 mailbox = input('请输入你的邮箱:') password = input('请输入你的密码:') receiver = input('请输入收件人的邮箱') #爬取数据 def foods(): url = 'http://www.xiachufang.com/explore/' headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36'} res = requests.get(url,headers = headers) soup = BeautifulSoup(res.text,'html.parser') list_foods = soup.find_all('div',class_ = 'info pure-u') list_all = [] for food in list_foods: title = food.find('a').text.strip() herf = 'http://www.xiachufang.com' + food.find('a')['href'] pei_l = food.find('p',class_ = 'ing ellipsis').text.strip() list_all.append([title,herf,pei_l]) return list_all #发送邮件 def send_email(list_all): global mailbox,password,receiver #设置为全局变量 mailhost = 'smtp.qq.com' qqmail = smtplib.SMTP() qqmail.connect(mailhost,46) qqmail.login(mailbox,password) content = list_all massage = MIMEText(content,'plain','utf-8') subject = '本周最受欢迎菜谱' message['subject'] = Header(subject,'utf-8') try: qqmail.sendmail(mailbox,receiver,message.as_string()) print('邮件发送成功') except: print('邮件发送失败') qqmail.quit() #定时执行任务 def job(): print('开始执行') list_all = foods() #调取爬取数据的函数并将结果赋值给新变量 send_email(list_all) #调取发送邮件的函数,并传入邮件内容 print('任务完成') schedule.every().day.at("10:30").do(job) #设定每天10:30执行任务 while True: #当符合条件的情况下就执行任务 schedule.run_pending() time.sleep(2) Traceback (most recent call last): File "D:\hello-world.py\youjian4.py", line 10, in <module> qqmail.connect(mailhost,465) File "D:\py\lib\smtplib.py", line 338, in connect (code, msg) = self.getreply() File "D:\py\lib\smtplib.py", line 394, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed 总是出现这个问题,请问该怎么解决

'str' object has no attribute 'get'咋解决?

本人学医,凭兴趣自学python,真心不易,现在遇到一个问题:在写一个简单的注册提交页面,是想通过class将数据存储到本地的txt文件,在输入username和password,submit到register/add时,但遇到了下面的问题: ![图片说明](https://img-ask.csdn.net/upload/201801/27/1517032413_303388.jpg) 请各位大神帮助看是什么问题。 下面是源代码,看看还有没有其他什么问题。谢谢! app.py ``` from flask import ( Flask, render_template, request, redirect, ) from Models import (Users, Requirements) import time import os app = Flask(__name__) @app.route('/', methods=['GET']) def index(): return render_template('/index.html') @app.route('/login') def login(): return render_template('/login.html') @app.route('/register') def register(): return render_template('/register.html') @app.route('/register/add', methods=['POST']) def register_add(): if request.method == 'POST': form = request.form print('打印', form) u = Users.new(form) u.save() return redirect('/login') @app.route('/post', methods=['GET']) def post_message(): return render_template('/post.html') @app.route('/post/add', methods=['POST']) def post_add(): if request.method == 'POST': form = request.form u = Requirements(form) u = Requirements.new(form) u.save() return redirect('/post') if __name__ == '__main__': config = dict( debug=True, host='0.0.0.0', port=2000, ) app.run(**config) ``` Model.py ``` from random import Random import json import os def save(data, path): m = json.dumps(data, ensure_ascii=False) # path = os.path.dirname(__file__) with open(path, 'a+') as f: f.read() f.write(m + '\n') f.close() def load(path): with open(path, 'r', encoding='utf-8') as f: s = f.read() m = json.dumps(s, ensure_ascii=False) print('加载', type(m), m) t = json.loads(m) print('加载', type(t), t) return t def random_str(randomlength=16): s = '' chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789' length = len(chars) - 1 random = Random() for i in range(randomlength): s += chars[random.randint(0, length)] return s class Model(object): @classmethod def db_path(cls): root = os.path.dirname(__file__) classname = cls.__name__ path = '{}/data/{}.txt'.format(root, classname) return path @classmethod def all(cls): """ all 方法(类里面的函数叫方法)使用 load 函数得到所有的 models """ path = cls.db_path() models = load(path) ms = [cls.new(m) for m in models] return ms @classmethod def new(cls, form): m = cls(form) return m def save(self): models = self.all() path = self.db_path() l = [m.__dict__ for m in models] save(l, path) class Users(Model): def __init__(self, form): self.id = random_str() self.username = form.get('username', '') self.password = form.get('password', '') class Requirements(Model): def __init__(self, form): self.id = form.get('id', None) self.province = form.get('province', '') self.city = form.get('city', '') self.post_content = form.get('post_content', '') self.contact_requirement_method = form.get('contact_requirement_method', '') ``` 最后搞定了,采取了下面这种方式,然后有修改了Model部分内容 ``` if request.method == 'POST': formdata = request.form form = formdata.to_dict() u = Users.new(form) u.save() ```

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

华为初面+综合面试(Java技术面)附上面试题

华为面试整体流程大致分为笔试,性格测试,面试,综合面试,回学校等结果。笔试来说,华为的难度较中等,选择题难度和网易腾讯差不多。最后的代码题,相比下来就简单很多,一共3道题目,前2题很容易就AC,题目已经记不太清楚,不过难度确实不大。最后一题最后提交的代码过了75%的样例,一直没有发现剩下的25%可能存在什么坑。 笔试部分太久远,我就不怎么回忆了。直接将面试。 面试 如果说腾讯的面试是挥金如土...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

win10暴力查看wifi密码

刚才邻居打了个电话说:喂小灰,你家wifi的密码是多少,我怎么连不上了。 我。。。 我也忘了哎,就找到了一个好办法,分享给大家: 第一种情况:已经连接上的wifi,怎么知道密码? 打开:控制面板\网络和 Internet\网络连接 然后右击wifi连接的无线网卡,选择状态 然后像下图一样: 第二种情况:前提是我不知道啊,但是我以前知道密码。 此时可以利用dos命令了 1、利用netsh wlan...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

带了6个月的徒弟当了面试官,而身为高级工程师的我天天修Bug......

即将毕业的应届毕业生一枚,现在只拿到了两家offer,但最近听到一些消息,其中一个offer,我这个组据说客户很少,很有可能整组被裁掉。 想问大家: 如果我刚入职这个组就被裁了怎么办呢? 大家都是什么时候知道自己要被裁了的? 面试软技能指导: BQ/Project/Resume 试听内容: 除了刷题,还有哪些技能是拿到offer不可或缺的要素 如何提升面试软实力:简历, 行为面试,沟通能...

!大部分程序员只会写3年代码

如果世界上都是这种不思进取的软件公司,那别说大部分程序员只会写 3 年代码,恐怕就没有程序员这种职业。

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

HTTP与HTTPS的区别

面试官问HTTP与HTTPS的区别,我这样回答让他竖起大拇指!

程序员毕业去大公司好还是小公司好?

虽然大公司并不是人人都能进,但我仍建议还未毕业的同学,尽力地通过校招向大公司挤,但凡挤进去,你这一生会容易很多。 大公司哪里好?没能进大公司怎么办?答案都在这里了,记得帮我点赞哦。 目录: 技术氛围 内部晋升与跳槽 啥也没学会,公司倒闭了? 不同的人脉圈,注定会有不同的结果 没能去大厂怎么办? 一、技术氛围 纵观整个程序员技术领域,哪个在行业有所名气的大牛,不是在大厂? 而且众所...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

美团面试,问了ThreadLocal原理,这个回答让我通过了

他想都想不到,ThreadLocal我烂熟于心

大牛都会用的IDEA调试技巧!!!

导读 前天面试了一个985高校的实习生,问了他平时用什么开发工具,他想也没想的说IDEA,于是我抛砖引玉的问了一下IDEA的调试用过吧,你说说怎么设置断点...

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

程序员是做全栈工程师好?还是专注一个领域好?

昨天,有位大一的同学私信我,说他要做全栈工程师。 我一听,这不害了孩子么,必须制止啊。 谁知,讲到最后,更确定了他做全栈程序员的梦想。 但凡做全栈工程师的,要么很惨,要么很牛! 但凡很牛的,绝不是一开始就是做全栈的! 全栈工程师听起来好听,但绝没有你想象的那么简单。 今天听我来给你唠,记得帮我点赞哦。 一、全栈工程师的职责 如果你学习编程的目的只是玩玩,那随意,想怎么学怎么学。...

立即提问
相关内容推荐