错误400 - 来自PHP请求的Flask request.get_data()的错误请求

I'm doing an internal API across my servers. I want to transfer some JSON strings from PHP to Python.

On Python, I have this code:

from flask import request
from flask import jsonify
...

@app.route('/database/<string:token>', methods=['POST', 'GET'])
def sync(token):
    if token not in VALID_TOKENS:
        ...

    json = request.get_json(force=True)
    ...

...
if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=False, port=6000)

On PHP-side, I have:

$payload = $datafromdatabase; 
$payload = json_encode($payload); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
curl_setopt($ch, CURLOPT_URL, $endpoint); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($payload))                                                                       
);
$result = curl_exec($ch); 

But Flask returns me, at every request:

127.0.0.1 - - [19/Feb/2017 20:08:00] "POST /database/token HTTP/1.1" 400 -

P.S: On Python, request.data and request.args are both None.

P.P.S.: Using requests.post(url, json=data) in Python works.

douxie0824
douxie0824 我编辑了,但问题不在于它。
3 年多之前 回复
dtlab08822
dtlab08822 $data_string在哪里定义?你正在计算来自那个未知变量的内容长度,而不是来自$payload
3 年多之前 回复
dongu189744321158
dongu189744321158 在调试模式下运行flask:app.run(host='0.0.0.0',debug=True,port=6000)。怎么了?
3 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
node.js-socketio与Python-socketio通信问题

**问题概述**:服务端接收不到前端(客户端)发到服务端的请求 **主要问题**:服务端接收不到前端发到服务端的请求,同样前端也接收不到服务端发来的数据。 当有客户端进行连接的时候,服务器端控制台可以打印出客户端GET请求的响应码(400)和客户端的身份信息(sid),当有客户端关闭的时候也可以打印出消息。 考虑过前后端的socket.io版本差异,但经过测试后已经基本排除 ​ 测试方法是:前端使用node.js写的服务器,版本无论是1.x还是2.x都是可以正常工作的。 考虑过CORS跨域请求问题,但经过测试也可以大致排除 ​ 测试方法是:首先前端的人确认在客户端上已经处理过这个问题,再者前端使用node.js写的服务器尝试删除掉关于跨域请求的任何设置依旧可以正常工作。 考虑过命名空间问题,但经过测试已经排除 **尝试过使用Flask框架的扩展包Flask-socketio进行连接/数据收发** 代码示例: ```python # -*- encoding: utf-8 -*- from flask import Flask def create_app(): app = Flask(__name__) socketio.init_app(app) return app app = create_app() @socketio.on('test', namespace='/test') def test(data): print('客户端插入的消息', data) emit('message', data, broadcast=True) if __name__ == '__main__': app.debug = True socketio.run(app, host='0.0.0.0', port=8000, debug=True, log_output=True) ``` **尝试过使用python-socketio包进行连接/数据收发** 代码示例: ```python from flask import Flask sio = socketio.Server(async_mode='threading', cors_allowed_origins='*', engineio_logger=True) app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' app.wsgi_app = socketio.WSGIApp(sio, app.wsgi_app) @sio.event def connect(sid, environ): print('客户端已连接', sid) @sio.event def disconnect(sid): print('连接断开 ', sid) @sio.event def login_request(data): # 数据收发 print(data) sio.emit('login_response',[responseData]) if __name__ == '__main__': app.run(host='0.0.0.0', port=8000, debug=True, threaded=True) ``` 尝试过使用基于Django框架的Django-socketio,但是由于Django框架过于庞大功能太多不够灵活,以及路由问题,在尝试使用socketio的时候没能驾驭的了,完全连接不上。失败。 **前端的状态码一直是400或101** _开发系统环境尝试过:CentOS,Ubuntu,windows_

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属性 请教大家如何解决这个问题

python flask_sqlalchemy如何维护一个全局查询结果

在我的webapp中,每个页面都要用到同一个一般不会变化的查询结果,为避免每次访问都需查询一次这个变量,我在views.py中弄了一个全局变量ADMIN_NOTES ``` ADMIN_NOTES=Note.query.filter_by(author_id=ADMIN.id).all() ``` 而当ADMIN_NOTE会发生变化时,如此时管理员又写入了一个新note,则重新查询数据库获得最新的ADMIN_NOTE的值,尽量减少访问数据库的次数 我本想这么实现的(中间部分不重要的代码省略了) ``` #全局变量 ADMIN_NOTES=Note.query.filter_by(author_id=ADMIN.id).all() #写入新note的函数1 @app.route('/new_note',methods=['GET','POST']) def new_note(): global ADMIN_NOTES data=json.loads(request.get_data()) note=Note(title=data['note_title'],upload_time=datetime.utcnow()) db.session.add(note) db.session.commit() #若是管理员写入新note,则重新查询并修改全局变量ADMIN_NOTES if note.author.nickname=='ADMIN': ADMIN_NOTES=Note.query.filter_by(author_id=ADMIN.id).all() KAFENUT_NOTES[0].author.nickname #能正确访问ADMIN_NOTES print(len(ADMIN_NOTES)) #正确访问ADMIN_NOTES resp['success']=True resp['text']='Upload successfully!' resp['url']=url_for('note',note_id=note.id,nickname=note.author.nickname) #浏览器接受到服务器的json之后跳转到,resp[url]所指示的页面,即下面这个页面 return json.dumps(resp) #返回note页面的函数2 @app.route('/<nickname>/note/<note_id>',methods=['GET','POST']) def note(nickname,note_id): global ADMIN_NOTES user=User.query.filter_by(nickname=nickname).first() note=Note.query.filter_by(id=note_id).first() if request.method=='GET': note.view_num+=1 db.session.add(note) db.session.commit() for nnote in ADMIN_NOTES: print(nnote.author.nickname) #出错位置 return render_template('note_page.html',note=note,admin_notes=ADMIN_NOTES) ``` 然而问题也正出在这里,当管理员写入新的note之后(即ADMIN_NOTES这个全局变量发生变化之后)重新查询的语句虽然在函数1中执行了(print出的note数量是写入新note之后的数量,)。但当用户根据函数1返回的json跳转到函数2的时候,函数2内就无法正确访问ADMIN_NOTES,准确来说无法访问nnote.author.nickname,其中author是note表用author_id这个外键连接到user表得到的,错误栈如下 ``` Traceback (most recent call last): File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise raise value File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise raise value File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "E:\vs\python\AwesomeWebApp\AwesomeWebApp\app\views.py", line 232, in note print(nnote.author.nickname) #let author.id be preloaded File "C:\Users\MSI-1\Anaconda3\lib\site-packages\sqlalchemy\orm\attributes.py", line 282, in __get__ return self.impl.get(instance_state(instance), dict_) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\sqlalchemy\orm\attributes.py", line 710, in get value = self.callable_(state, passive) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\sqlalchemy\orm\strategies.py", line 688, in _load_for_state % (orm_util.state_str(state), self.key) sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <Note at 0x26de5f41198> is not bound to a Session; lazy load operation of attribute 'author' cannot proceed (Background on this error at: http://sqlalche.me/e/bhk3) ``` sqlalchemy报出detached错误 sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <Note at 0x26de5f41198> is not bound to a Session; lazy load operation of attribute 'author' cannot proceed (Background on this error at: http://sqlalche.me/e/bhk3) 这该怎么解决?或者还有什么其他方法实现:在我的webapp中,每个页面都要用到同一个一般不会变化的查询结果,为避免每次访问都需查询一次这个一般不会变量,我在views.py中弄了一个全局变量ADMIN_NOTES。而当ADMIN_NOTE会发生变化时,如此时管理员又写入了一个新note,则重新查询数据库获得最新的ADMIN_NOTE的值,尽量减少访问数据库的次数

Firestore截止日期大集合超出了例外

<div class="post-text" itemprop="text"> <p>I'm trying to read bigger collections from Google Firestore for testing and archiving purposes. I'm hitting some interesting errors when I try to get all documents from collections with more than 6k documents in them.</p> <h1>Naive Python solution</h1> <p>My first try was using the Python <code>google-cloud-firestore</code> (version 0.30.0) library.</p> <pre class="lang-py prettyprint-override"><code>source_client = firestore.Client() source = source_client.collection(collection) source_data = source.get() counter = 0 for f in source_data: app.logger.info(f.id) counter += 1 if counter % 100 == 0: app.logger.info('%s %d', datetime.now(), counter) app.logger.info('%s Finally read all %d documents', datetime.now(), counter) </code></pre> <p>Which gives the following output:</p> <pre><code>INFO:flask.app:2018-11-08 09:49:03.923795 6400 INFO:flask.app:2018-11-08 09:49:04.115410 6500 ... INFO:flask.app:2018-11-08 09:49:03.923795 6400 INFO:flask.app:2018-11-08 09:49:04.115410 6500 WARNING:flask.app:2018-11-08 09:49:04.128478 copy brocken by exception Traceback (most recent call last): File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise raise value File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise raise value File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/carsten/projects/transfertool/firestore/transfertool/main.py", line 142, in transfer count_collection(source_collection) File "/home/carsten/projects/transfertool/firestore/transfertool/main.py", line 94, in count_collection for f in source_collection.offset(1000).get(): File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/google/cloud/firestore_v1beta1/query.py", line 588, in get for index, response_pb in enumerate(response_iterator): File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 83, in next six.raise_from(exceptions.from_grpc_error(exc), exc) File "&lt;string&gt;", line 3, in raise_from # Permission is hereby granted, free of charge, to any person obtaining a copy google.api_core.exceptions.DeadlineExceeded: 504 Deadline Exceeded </code></pre> <p>Which seems to be caused by a quota. Even if I cannot see it <a href="https://firebase.google.com/docs/firestore/quotas" rel="nofollow noreferrer">here</a>. It seems to be time based because when I run with small sleeps in between elements I get less throughput and get the exception after ~50s.</p> <h1>Paging with Python</h1> <p>For exactly this problem there is a paging part in this library. As my application should not care about what kind of data I try to transfer I cannot use the <code>start_after</code> interface but there is still an offset interface with which I can at least read in batches.</p> <pre class="lang-py prettyprint-override"><code>for f in source_collection.offset(last_read_offset).get(): </code></pre> <p>Which gives me correct results as long as the <code>last_read_offset</code> is below 1001. If I start with an offset of 1000 I can get results until I get the <code>google.api_core.exceptions.DeadlineExceeded exception</code> from above. But when I start with something bigger I get:</p> <pre><code>Traceback (most recent call last): File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise raise value File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise raise value File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/carsten/projects/transfertool/firestore/transfertool/main.py", line 144, in transfer count_collection(source_collection) File "/home/carsten/projects/transfertool/firestore/transfertool/main.py", line 94, in count_collection for f in source_collection.offset(1001).get(): File "/home/carsten/projects/transfertool/venv/lib/python3.6/site-packages/google/cloud/firestore_v1beta1/query.py", line 599, in get raise ValueError(msg) ValueError: Unexpected server response. All responses other than the first must contain a document. The response at index 1 was read_time { seconds: 1541668338 nanos: 420813000 } skipped_results: 1 </code></pre> <p>Looking at the library code it seems that the backend is sending a message which is interpreted as invalid.</p> <h1>Retry via node.js</h1> <p>Okay maybe my code or the Python client library is bugged. Let's try with node.</p> <pre><code>const admin = require('firebase-admin'); admin.initializeApp({ credential: admin.credential.applicationDefault() }); var db = admin.firestore(); admin.firestore().settings( { timestampsInSnapshots: true }) var counter = 0 console.log('Read collection') db.collection(collection).get() .then(querySnapshot =&gt; { querySnapshot.forEach(documentSnapshot =&gt; { counter++; }); console.log(counter) }) .catch( error =&gt; { console.log(error) }); </code></pre> <p>Which does the same as the python library even if the timeout is much more clearly 60s.</p> <pre><code>[2018-11-09T08:36:30.992Z] App listening on port 8080 [2018-11-09T08:36:30.993Z] Press Ctrl+C to quit. [2018-11-09T08:36:37.390Z] Read collection [2018-11-09T08:37:37.406Z] { Error: 4 DEADLINE_EXCEEDED: Deadline Exceeded at Object.exports.createStatusError (/home/carsten/projects/node_modules/grpc/src/common.js:87:15) at ClientReadableStream._emitStatusIfDone (/home/carsten/projects/node_modules/grpc/src/client.js:235:26) at ClientReadableStream._readsDone (/home/carsten/projects/node_modules/grpc/src/client.js:201:8) at /home/carsten/projects/node_modules/grpc/src/client_interceptors.js:679:15 code: 4, metadata: Metadata { _internal_repr: {} }, details: 'Deadline Exceeded' } </code></pre> <p>Has anyone similar experiences or a good hint how to continue?</p> <p>PS: The <code>exportDocument</code> / <code>importDocument</code> interface is not enough as we sometimes have to adjust the data after reading. And I have no clue what kind of format Firestore is exporting to Google Cloud Storage or how to transform it.</p> <h1>Edit: golang</h1> <p>And for the heck of it i tried the golang api.</p> <pre><code>log.Println("Collecting data") snapshotIter := client.Collection(collection.(string)).Documents(ctx) defer snapshotIter.Stop() if err != nil { log.Fatalln(err) } i := 0 for { _, err := snapshotIter.Next() if err == iterator.Done { break } if err != nil { log.Fatalln(err) } if i % 100 == 0{ log.Println(i) } i++ } log.Println("Done") </code></pre> <p>Which runs into the same timeout as expected.</p> <pre><code>2018/11/12 15:01:20 Collecting data 2018/11/12 15:01:21 0 2018/11/12 15:01:21 100 2018/11/12 15:01:21 200 2018/11/12 15:01:21 300 2018/11/12 15:01:21 400 2018/11/12 15:01:22 500 2018/11/12 15:01:22 600 2018/11/12 15:01:22 700 .... 2018/11/12 15:02:22 29800 2018/11/12 15:02:23 29900 2018/11/12 15:02:23 rpc error: code = DeadlineExceeded desc = The datastore operation timed out, or the data was temporarily unavailable. </code></pre> <p>But in addition the offset is working fine:</p> <pre><code>snapshotIter := client.Collection(collection.(string)).Offset(30000).Documents(ctx) </code></pre> </div>

从Flask发送POST请求到PHP脚本

<div class="post-text" itemprop="text"> <p>I'm trying to send a POST request to a PHP script from Flask. I am using a Datatables Editor to get information from a backend database. Datatables will send a POST request to get the data it needs when DOM is ready. However, I'm getting the following error:</p> <blockquote> <p>Method Not Allowed The method is not allowed for the requested URL.</p> </blockquote> <p>Here's the route:</p> <p></p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>@bp.route('/my_php', methods=['GET', 'POST']) def php_post(): url = 'http://localhost:5000/static/datatables-plugins/Editor-PHP-1.7.4/examples/php/staff.php' headers = { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Encoding': 'gzip, deflate, br', 'X-Requested-With': 'XMLHttpRequest' } data = urllib.parse.urlencode(request.form).encode('utf-8') resp = requests.post(url, data=data, headers=headers) return json.dumps(resp.content).encode('utf-8')</code></pre> </div> </div> <p>I think this may have to do with specifying allowed methods, however I don't know how to explicitly allow for GET/POST methods when a request for another URL is called <em>within</em> the Flask route. </p> </div>

python 爬虫 too many values to unpack (expected 2)

``` import urllib.request as ur header =( "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 QIHU 360EE") opener = ur.build_opener() url = "https://www.jianshu.com/p/2d8e4416c077" data = opener.open(url).read() ``` 报错 报错 报错 ``` ValueError Traceback (most recent call last) <ipython-input-63-36e685c3559f> in <module> 1 url = "https://www.jianshu.com/p/2d8e4416c077" ----> 2 data = opener.open(url).read() D:\softs\anaconda\lib\urllib\request.py in open(self, fullurl, data, timeout) 521 for processor in self.process_request.get(protocol, []): 522 meth = getattr(processor, meth_name) --> 523 req = meth(req) 524 525 response = self._open(req, data) D:\softs\anaconda\lib\urllib\request.py in do_request_(self, request) 1266 if not request.has_header('Host'): 1267 request.add_unredirected_header('Host', sel_host) -> 1268 for name, value in self.parent.addheaders: 1269 name = name.capitalize() 1270 if not request.has_header(name): ValueError: too many values to unpack (expected 2) ``` 请问如何解决?

微信小程序与flask服务器交互 wx.request

``` var uploadTask = wx.request({ url: 'http://127.0.0.1:5000/getimage', data:{ //this.data.src本地上传的图片所在的路径 file: JSON.stringify(this.data.src) }, method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded' }, success: function (res) { console.log(res.data); } ``` 微信小程序开发工具报错: ![图片说明](https://img-ask.csdn.net/upload/201905/08/1557282709_960791.png) Spyder端: ``` import os.path from flask import Flask from flask import app,request app = Flask(__name__) #创建1个Flask实例 basedir = os.path.abspath(os.path.dirname(__file__)) #定义一个根目录 用于保存图片用 @app.route('/getimage',methods=['POST']) def getimage(): #获取图片文件 name = file img = request.files.get('file') #定义一个图片存放的位置 存放在static下面 path = basedir+"/static/img/" #图片名称 imgName = img.filename #图片path和名称组成图片的保存路径 file_path = path+imgName #保存图片 img.save(file_path) #url是图片的路径 url = '/static/img/'+imgName return url if __name__ == "__main__": app.run() ``` IPython console报错: ![图片说明](https://img-ask.csdn.net/upload/201905/08/1557282977_917689.png)

萌新提问!:flask ajax 下载服务端文件,请求能成功,但是文件下载不下来,是为什么?

需求是一个简单的页面,用户输入要想查询数据的时间(如:2019-03-31) 然后后端收到数据,从数据库等地方获取数据 处理之后 做成pandas的dataframe,然后pandas的to_excel 生成Excel文件保存在服务端中,用户点击下载按钮 下载文件。 现在遇到的问题是: 请求能成功,状态码200 但是无法下载文件。 跪求大佬!! 这是后端代码 ```python @app.route('/') def html(): return render_template('download.html') @app.route('/download', methods=['POST']) def downloads(time): # 获取时间数据 time = request.args.get() print(time) # filename=StringIO() # time = request.get_json()["time"] print(time) filename = "{}.xlsx".format(time) writer = pd.ExcelWriter(filename) # df3,df2,df4 是通过时间从数据库获取的数据 转dataframe df3,df2,df4 = get_excel(time) gc = GetCount(time) # hb_df,sc_df 同上 获取数据转dataframe hb_df = gc.get_hb_uv() sc_df = gc.get_sc_uv() df3.to_excel(writer,sheet_name="1-{}".format(time), index=False) df2.to_excel(writer,sheet_name="2-{}".format(time), index=False) df4.to_excel(writer,sheet_name="3-{}".format(time), index=False) hb_df.to_excel(writer,sheet_name="4-{}".format(time), index=False) sc_df.to_excel(writer,sheet_name="5-{}".format(time), index=False) writer.save() if os.path.isfile(os.path.join(basedir, filename)): print(os.path.join(basedir, filename)) response = make_response(send_from_directory(basedir, filename, as_attachment=True)) response.headers["Content-Disposition"] = "attachment; filename={}".format(filename) return response ``` 这是前端代码 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>数据下载</title> <style> .main { margin: 100px auto; width: 500px; border: 1px solid #ddd; border-radius: 5px; padding: 100px 50px; } </style> </head> <body> <div class="main"> <h2>数据下载</h2> <span>请输入要查询的时间:</span><input type="text" placeholder="时间格式为:2019-01-01" id="time"> <br> <button type="button" onclick="download()">下载数据</button> </div> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> function download(){ var params = { time: $('#time').val() }; if($('#time').val() === '') { alert('请输入时间') } else { $.ajax({ type: 'post', url: '/download', data: JSON.stringify(params), contentType: "application/json", datatype: 'json', success: function(data){ }, error: function(err){ alert('出错了:' + err) } }) } } </script> </html> ```

flask项目,从redis取值一直为None

我把生成的图片验证码按编号保存在redis中,然后按编号从redis中取值,但是返回一直为None,但是如果用redis_store.get("对应的id")就能取到值 ``` #coding:utf8 from . import api from ihome.utils.captcha.captcha import captcha from ihome import redis_store,constants,db from ihome.models import User from ihome.utils.response_code import RET from ihome.libs.yuntongxun.sms import CCP from flask import current_app,jsonify,make_response,request import random @api.route("/image_codes/<image_code_id>") def get_image_code(image_code_id): """ 获取图片验证码 :param image_code_id: 图片验证码编号 :return: 正常:验证码图片 异常:返回json """ # 业务逻辑处理 # 生成验证码图片 # 名字,真实文本, 图片数据 name,text,image_data=captcha.generate_captcha() # 将验证码真实值与编号保存到redis中, 设置有效期 # redis: 字符串 列表 哈希 set # "key": xxx # 使用哈希维护有效期的时候只能整体设置 # "image_codes": {"id1":"abc", "":"", "":""} 哈希 hset("image_codes", "id1", "abc") hget("image_codes", "id1") # 单条维护记录,选用字符串 # "image_code_编号1": "真实值" # "image_code_编号2": "真实值" # redis_store.set("image_code_%s"%image_code_id,text) # redis_store.expire("image_code_%s"%image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES) # 记录名字              有效期               记录值           try: redis_store.setex("image_code_%s"%image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text) except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DATAERR,errmsg="save msg id error") #返回图片 resp=make_response(image_data) resp.headers["Content-Type"]="image/jpg" return resp @api.route("/sms_codes/<re(r'1[34578]\d{9}'):mobile>") def get_sms_code(mobile): """获取短信验证码 """ #获取参数 image_code=request.args.get("image_code") image_code_id=request.args.get("image_code_id") #校验参数 if not all([image_code_id,image_code]): #表示参数不完整 return jsonify(errno=RET.PARAMERR,errmsg="incomplete parameter") #业务逻辑处理 #从redis中取出真实的图片验证码 try: real_image_code = redis_store.get("image_code_%s"%image_code_id) print real_image_code except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR,errmsg="database error") #判断图片验证码是否过期 if real_image_code is None: return jsonify(errno=RET.NODATA,errmsg="image not exit or overdue") # 删除redis中的图片验证码,防止用户使用同一个图片验证码验证多次 try: redis_store.delete("image_code_%s" % image_code_id) except Exception as e: current_app.logger.error(e) #与用户填写的值进行对比 if real_image_code.lower() != image_code.lower(): return jsonify(errno=RET.DATAERR,errmsg="image error") # 判断对于这个手机号的操作,在60秒内有没有之前的记录,如果有,则认为用户操作频繁,不接受处理 try: send_flag = redis_store.get("send_sms_code_%s" % mobile) except Exception as e: current_app.logger.error(e) else: if send_flag is not None: # 表示在60秒内之前有过发送的记录 return jsonify(errno=RET.REQERR, errmsg=u"请求过于频繁,请60秒后重试") #判断手机号是否存在 try: user=User.query.filter_by(mobile=mobile).first() except Exception as e: current_app.logger.error(e) else: if user is not None: #表示手机号已经存在 return jsonify(errno=RET.DATAEXIST,errmsg="mobile is exist") #如果手机号不存在则生成短信验证码 sms_code="%06d"%random.randint(0,999999) #保存真实的短信验证码 try: redis_store.setex("sms_code_%s"%mobile,constants.MSG_CODE_REDIS_EXPIRES,sms_code) redis_store.setex("send_sms_code_%s"%mobile,constants.SEND_MSG_CODE_INTERNAL,1) except Exception as e: current_app.logger.error(e) jsonify(errno=RET.DBERR,errmsg="save code error") #发送短信 try: ccp=CCP() result=ccp.send_template_sms(mobile,[sms_code,int(constants.MSG_CODE_REDIS_EXPIRES/60)],1) except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.THIRDERR,errmsg="send abnormal") #返回值 if result==0: return jsonify(errno=RET.OK,errmsg="send success") else: return jsonify(errno=RET.SERVERERR,errmsg="send failed") ```

求助:flask login_user提示'int' object is not callable”

Flask在登录时,提示'int' object is not callable,请各位帮助看一下是什么问题? 根据traceback最后一部提示在getid时出现问题,源码解释要返回unicode id,不知是不是这个原因? 错误提示: ``` File "C:\Personal\Peoplefinder\venv\lib\site-packages\flask\app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "C:\Personal\Peoplefinder\Routes.py", line 66, in login login_user(user) File "C:\Personal\Peoplefinder\venv\lib\site-packages\flask_login\utils.py", line 161, in login_user user_id = getattr(user, current_app.login_manager.id_attribute)() TypeError: 'int' object is not callable ``` Taceback源码提示: ``` #: The default attribute to retreive the unicode id of the user ID_ATTRIBUTE = 'get_id' ``` 以下是代码: Routes.py ``` from flask import ( render_template, request, redirect, flash, url_for, Flask ) from Models import User from flask_login import LoginManager, login_user, logout_user , current_user , login_required from flask_sqlalchemy import SQLAlchemy from sqlalchemy import create_engine, MetaData import os app = Flask(__name__) path = os.path.dirname(__file__) path = path + '\data\data.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(path) app.config['SECRET_KEY'] = 'kdije29fuk_ksdusii2w' # engine = create_engine('sqlite:///' + path, echo=True) # metadata = MetaData(engine) **_** db = SQLAlchemy(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' login_manager.session_protection = 'strong' @app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'GET': return render_template('register.html') user = User(request.form['username'], request.form['password']) db.session.add(user) db.session.commit() flash('User successfully registered') return redirect(url_for('login')) @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') username = request.form['username'] password = request.form['password'] user = User.query.filter_by(username=username).first() print(user) t = user.verify_password(password) print(t) if user is not None and t is True: login_user(user) print('成功') return redirect(url_for('login')) else: flash('Username or Password is invalid', 'error') print('失败') return redirect(url_for('register')) if __name__ == '__main__': config = dict( debug=True, host='0.0.0.0', port=2000, ) app.run(**config) ``` models.py ``` from flask_login import UserMixin, login_manager, LoginManager from flask_sqlalchemy import SQLAlchemy from werkzeug.security import generate_password_hash, check_password_hash db = SQLAlchemy() class User(db.Model, UserMixin): __tablename__ = "users" id = db.Column('user_id', db.Integer, primary_key=True) username = db.Column('username', db.String(20), unique=True , index=True) password_hash = db.Column('password_hash', db.String(1000)) def __init__(self, username, password): self.username = username self.password = password @property def password(self): raise AttributeError('password is not a readable attribute/ password 不是一个可读属性。') @password.setter def password(self, password): self.password_hash = generate_password_hash(password, method='pbkdf2:sha256', salt_length=8) def verify_password(self, password): return check_password_hash(self.password_hash, password) @property def is_authenticated(self): return True @property def is_active(self): return True @property def is_anonymous(self): return False @property def get_id(self): return self.id def __repr__(self): return '<User %r>' % (self.username) ```

'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() ```

Flask blueprint: cannot import name 'main'

用Flask写了一个web服务器,在用Blue print时,提示 cannot import name'main'。 把blue print两行注释掉正常运行。百度了一下,有可能是import的顺序有错误 https://segmentfault.com/a/1190000010600365 但不确定是不是这个问题,如果是该怎么调整? Traceback提示: ``` Traceback (most recent call last): File "C:/Personal/Peoplefinder/app.py", line 21, in <module> from Routes import main File "C:\Personal\Peoplefinder\Routes.py", line 11, in <module> from Models import User File "C:\Personal\Peoplefinder\Models.py", line 4, in <module> from app import lm File "C:\Personal\Peoplefinder\app.py", line 21, in <module> from Routes import main ImportError: cannot import name 'main' ``` **源码: app.py , Models.py , Routes.py** app.py ``` from flask import Flask from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy import os app = Flask(__name__) path = os.path.dirname(__file__) path = path + '\data\data.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(path) app.config['SECRET_KEY'] = 'kdije29fuk_ksdusii2w' db = SQLAlchemy(app) lm = LoginManager() lm.init_app(app) lm.login_view = 'login' lm.session_protection = 'strong' from Routes import main app.register_blueprint(main) if __name__ == '__main__': config = dict( debug=True, host='0.0.0.0', port=2000, ) app.run(**config) ``` Models.py ``` from flask_login import UserMixin, login_manager from flask_sqlalchemy import SQLAlchemy from werkzeug.security import generate_password_hash, check_password_hash from app import lm db = SQLAlchemy() class User(db.Model, UserMixin): __tablename__ = "users" id = db.Column('user_id1', db.Integer, primary_key=True) username = db.Column('username', db.String(20), unique=True , index=True) password_hash = db.Column('password_hash', db.String(1000)) def __init__(self, username, password): self.username = username self.password = password @property def password(self): raise AttributeError('password is not a readable attribute/ password 不是一个可读属性。') @password.setter def password(self, password): self.password_hash = generate_password_hash(password, method='pbkdf2:sha256', salt_length=8) def verify_password(self, password): return check_password_hash(self.password_hash, password) @property def is_authenticated(self): return True @property def is_active(self): return True @property def is_anonymous(self): return False def __repr__(self): return '<User %r>' % (self.username) @lm.user_loader def load_user(user_id): return User.query.get(int(user_id)) ``` Routes.py ``` from flask import ( render_template, request, redirect, flash, url_for, session, Blueprint ) from Models import User from flask_login import login_user from app import db main = Blueprint('main', __name__) @main.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'GET': return render_template('register.html') user = User(request.form['username'], request.form['password']) db.session.add(user) db.session.commit() flash('User successfully registered') return redirect(url_for('login')) @main.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') username = request.form['username'] password = request.form['password'] u = User.query.filter_by(username=username).first() v = u.verify_password(password) if u is not None and v is True: login_user(u) print(session) print('成功') return redirect(url_for('index')) else: flash('Username or Password is invalid', 'error') print('失败') return redirect(url_for('register')) @main.route('/', methods=['GET']) def index(): if request.method == 'GET': return render_template('index.html') ```

发布400(错误请求)

<div class="post-text" itemprop="text"> <p>I'm attempting to submit my form, but it continually fails as there's something wrong with the POST. I'm unsure where/what exactly is causing the server to not process the request whether it's related to syntax, request routing, etc. I've also commented out every line related to file uploads, as well as comment out the if (validated) statement. There are no errors in the console as a result of this, but the form submission still fails. I'd appreciate any help/direction thanks.</p> <p>I get this error message when I submit the form:</p> <p>POST <a href="http://127.0.0.1:5051/register/" rel="nofollow noreferrer">http://127.0.0.1:5051/register/</a> 400 (BAD REQUEST)</p> <p>views.py</p> <pre><code>@blueprint.route("register/", methods=['GET', 'POST']) def register(): """Renders register page.""" form = RegisterForm() if request.method == 'POST': if not form.validate_on_submit(): return render_template('main/register.html', page_title="Service Registration", form=form, form_success=False, media_types=current_app.config["ACCEPTED_" "MEDIA_TYPE"]) ticket, err = create_ticket2(customer_id, organization + " " + venue_name + " " + street + " " + country + " " + teamviewquestion + " " + teamviewerid + " " + deviations + " " + deviationsnotes + " " + displaydirector + " " + composer + " " + decryptor + " " + motionrocket + " " + othersoftware, location=location) if err: return render_template('main/register.html', page_title="Service Registration", form=form, form_success=False, message=err, media_types=current_app.config["ACCEPTED_" "MEDIA_TYPE"]) else: success_msg = "Error" .format(ticket.get('id')) return render_template('main/register.html', page_title="Service Registration", form=form, form_success=True, message=success_msg, media_types=current_app.config["ACCEPTED_" "MEDIA_TYPE"]) return render_template('main/register.html', page_title="Service Registration", form=form, media_types=current_app.config["ACCEPTED_" "MEDIA_TYPE"]) """Handles file upload POSTs.""" first_name = request.form.get("first_name") last_name = request.form.get("last_name") name = request.form.get("first_name") + " " + request.form.get("last_name") email = request.form.get("email") filename = request.form.get("filename") file_type = request.form.get("file_type") if filename == '': response = make_response("No selected file") return response, 400 if check_file_type(file_type): filename = clean_filename(filename) filename = secure_filename(filename) filename = unique_filename(filename) response = generate_presigned_post(filename, file_type) # CREATE DB REFERENCE url = "http://nevcodocs.s3.amazonaws.com/Uploads/{}".format(filename) instance = CustomerFileUpload.query.filter_by(url=url).first() if not instance: instance = CustomerFileUpload(url=url, email=email, name=name) db.session.add(instance) db.session.commit() else: instance.update(created_at=datetime.utcnow()) return response, 200 </code></pre> <p>js (ticket submission function)</p> <pre><code>$('#ticket-form').submit(function(event) { if (validated) { $('#filename').val($('#upload').val()); $.ajax({ type: 'POST', url: '/register/', data: $('#ticket-form').serialize() }).done(function(data) { var formData = new FormData(); for (var key in data.data) { formData.append(key, data.data[key]); } formData.append('file', $('#upload').prop('files')[0]); formData.append('csrf_token', '{{ csrf_token }}'); var req = new XMLHttpRequest(); req.onload = function() { showSpinner(false); $('#ticket-form').removeClass("support-form-show"); $('#ticket-form').addClass("support-form-hide"); }; req.onerror = function() { showSpinner(false); $('#ticket-form-failed').removeClass("support-form-hide"); $('#ticket-form-failed').addClass("support-form-show"); }; req.open('POST', '/register/'); req.send(formData); }).fail(function(err) { showSpinner(false); $('#ticket-form-failed').removeClass("support-form-hide"); $('#ticket-form-failed').addClass("support-form-show"); }); } else { showSpinner(false); enableSubmit(true); } }); </code></pre> </div>

Flask的Ajax发布请求

<div class="post-text" itemprop="text"> <p>I am using AJAX to send a POST request to a Flask route, but I don't know how to get the post data in a format I can read.</p> <p>My route looks like this:</p> <pre><code>@app.route("/sendinvites", methods=["POST"]) @login_required def sendinvites(): print(request.get_data("emails")) return jsonify("done") </code></pre> <p>My AJAX looks as:</p> <pre><code>$.ajax({ type: "POST", dataType: "json", url: "/sendinvites", data: { emails : emails, usernames: usernames }, success: function(data) { console.log(data) } }); </code></pre> <p>An example of the data sent in the emails variable is:</p> <pre><code>0: Object { id: undefined, username: "me@mydomain.com" } </code></pre> <p>An example of the output from the route is:</p> <pre><code>b'emails%5B0%5D%5Busername%5D=me%40mydomain.com' </code></pre> <p>Does anyone know how I can get the post data into a dictionary object so it is easier to process?</p> </div>

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) ```

渲染模板FLASK

<div class="post-text" itemprop="text"> <p>I have a problem with reload page, when I click the button wchich is used to filtrate data witch using ajax script. In condition IF not working render template . Below sample code </p> <p>Python</p> <pre><code>def viewchallenges(): categories = Categories.query.all() if request.method=='POST': category_id=Categories.query.filter_by(category=request.form['name']).first() check=Challenge.query.filter_by(categorie_id=category_id.id).order_by(Challenge.timestamp.desc()).all() if not check: flash(_('not found')) else: page = request.args.get('page', 1, type=int) posts = Challenge.query.filter_by(categorie_id=category_id.id).order_by(Challenge.timestamp.desc()).paginate( page, current_app.config['POSTS_PER_PAGE'], False) next_url = url_for('main.viewchallenges', page=posts.next_num) \ if posts.has_next else None prev_url = url_for('main.viewchallenges', page=posts.prev_num) \ if posts.has_prev else None return render_template('viewChallanges.html', title=_('View Challenge'), posts=posts.items, next_url=next_url, prev_url=prev_url,categories=categories) page = request.args.get('page', 1, type=int) posts =Challenge.query.order_by(Challenge.timestamp.desc()).paginate( page,current_app.config['POSTS_PER_PAGE'], False) next_url = url_for('main.viewchallenges', page=posts.next_num) \ if posts.has_next else None prev_url = url_for('main.viewchallenges', page=posts.prev_num) \ if posts.has_prev else None return render_template('viewChallanges.html', title=_('View Challenge'), posts=posts.items, next_url=next_url, prev_url=prev_url,categories=categories) </code></pre> <p>HTML</p> <pre><code>{% for item_category in categories %} &lt;button class="btn btn-secondary fby_category"&gt;{{item_category.category}}&lt;/button&gt; {% endfor %} </code></pre> <p>AJAX</p> <pre><code> $('.fby_category').click(function(e) { var url = "{{ url_for('main.viewchallenges') }}"; e.preventDefault(); $.ajax({ type: "POST", url: url, data: { 'name': $(this).text() }, }); }); </code></pre> </div>

为什么HTTP request 出错 window.location.href 依然可以跳转

fetch的地址是乱写的 但是浏览器 为什么依然可以跳转 目标html 而且不报错 如果删window.location.href. 则会提示404 ``` var promise = fetch('/registerdfdfd', { method: 'post', body: userObjStr, headers: { 'Content-Type': 'application/json' } }).then(registrationSuccessful, registrationFailed); function registrationSuccessful() { window.location.href = '/profile/profile.template.client.html'; } function registrationFailed() { alert("oops") } } ```

python爬取豆瓣电影 一直报错 求解决

==== RESTART: C:\Users\123\AppData\Local\Programs\Python\Python36\类的学习.py ==== Traceback (most recent call last): File "C:\Users\123\AppData\Local\Programs\Python\Python36\类的学习.py", line 29, in <module> movies_list=get_review(getHtmlText(url)) File "C:\Users\123\AppData\Local\Programs\Python\Python36\类的学习.py", line 20, in get_review dict['name']=tag_li.find('span','titlt')[0].string TypeError: 'NoneType' object is not subscriptable ——代码如下————————————————————————————— import requests from bs4 import BeautifulSoup import bs4 def getHtmlText(url): try: r = requests.get(url, timeout = 30); r.raise_for_status(); r.encoding = r.apparent_encoding; return r.text; except: return "" def get_review(html): movies_list=[] soup=BeautifulSoup(html,"html.parser") soup=soup.find('ol','grid_view') for tag_li in soup.find_all('li'): dict={} dict['rank']=tag_li.find('em').string dict['name']=tag_li.find('span','titlt')[0].string dict['score']=tag_li.find('span','rating_num').string if(tag_li.find('span','inq')): dict['desc']=tag_li.find('span','inq').string movies_list.append(dict) return movies_list if __name__=='__main__': for i in range(10): url='http://movie.douban.com/top250?start=%s&filter=&type=' %(i*25) movies_list=get_review(getHtmlText(url)) for movie_dict in movies_list: print('电影排名:'+movie_dict['rank']) print('电影名称:'+movie_dict.get('name')) print('电影评分:'+movie_dict.get('score')) print('电影评词:'+movie_dict.get('desc','无评词')) print('------------------------------------------------------')

请问为什么后台获取不到表单数据

![图片说明](https://img-ask.csdn.net/upload/202002/02/1580621264_510387.png) ![图片说明](https://img-ask.csdn.net/upload/202002/02/1580621287_929596.png)![图片说明](https://img-ask.csdn.net/upload/202002/02/1580621300_411017.png)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

课程主要面向嵌入式Linux初学者、工程师、学生 主要从一下几方面进行讲解: 1.linux学习路线、基本命令、高级命令 2.shell、vi及vim入门讲解 3.软件安装下载、NFS、Samba、FTP等服务器配置及使用

我以为我对Mysql事务很熟,直到我遇到了阿里面试官

太惨了,面试又被吊打

Python代码实现飞机大战

文章目录经典飞机大战一.游戏设定二.我方飞机三.敌方飞机四.发射子弹五.发放补给包六.主模块 经典飞机大战 源代码以及素材资料(图片,音频)可从下面的github中下载: 飞机大战源代码以及素材资料github项目地址链接 ————————————————————————————————————————————————————————— 不知道大家有没有打过飞机,喜不喜欢打飞机。当我第一次接触这个东西的时候,我的内心是被震撼到的。第一次接触打飞机的时候作者本人是身心愉悦的,因为周边的朋友都在打飞机, 每

Python数据分析与挖掘

92讲视频课+16大项目实战+源码+¥800元课程礼包+讲师社群1V1答疑+社群闭门分享会=99元 &nbsp; 为什么学习数据分析? &nbsp; &nbsp; &nbsp; 人工智能、大数据时代有什么技能是可以运用在各种行业的?数据分析就是。 &nbsp; &nbsp; &nbsp; 从海量数据中获得别人看不见的信息,创业者可以通过数据分析来优化产品,营销人员可以通过数据分析改进营销策略,产品经理可以通过数据分析洞察用户习惯,金融从业者可以通过数据分析规避投资风险,程序员可以通过数据分析进一步挖掘出数据价值,它和编程一样,本质上也是一个工具,通过数据来对现实事物进行分析和识别的能力。不管你从事什么行业,掌握了数据分析能力,往往在其岗位上更有竞争力。 &nbsp;&nbsp; 本课程共包含五大模块: 一、先导篇: 通过分析数据分析师的一天,让学员了解全面了解成为一个数据分析师的所有必修功法,对数据分析师不在迷惑。 &nbsp; 二、基础篇: 围绕Python基础语法介绍、数据预处理、数据可视化以及数据分析与挖掘......这些核心技能模块展开,帮助你快速而全面的掌握和了解成为一个数据分析师的所有必修功法。 &nbsp; 三、数据采集篇: 通过网络爬虫实战解决数据分析的必经之路:数据从何来的问题,讲解常见的爬虫套路并利用三大实战帮助学员扎实数据采集能力,避免没有数据可分析的尴尬。 &nbsp; 四、分析工具篇: 讲解数据分析避不开的科学计算库Numpy、数据分析工具Pandas及常见可视化工具Matplotlib。 &nbsp; 五、算法篇: 算法是数据分析的精华,课程精选10大算法,包括分类、聚类、预测3大类型,每个算法都从原理和案例两个角度学习,让你不仅能用起来,了解原理,还能知道为什么这么做。

如何在虚拟机VM上使用串口

在系统内核开发中,经常会用到串口调试,利用VMware的Virtual Machine更是为调试系统内核如虎添翼。那么怎么搭建串口调试环境呢?因为最近工作涉及到这方面,利用强大的google搜索和自己

程序员的兼职技能课

获取讲师答疑方式: 在付费视频第一节(触摸命令_ALL)片头有二维码及加群流程介绍 限时福利 原价99元,今日仅需39元!购课添加小助手(微信号:csdn590)按提示还可领取价值800元的编程大礼包! 讲师介绍: 苏奕嘉&nbsp;前阿里UC项目工程师 脚本开发平台官方认证满级(六级)开发者。 我将如何教会你通过【定制脚本】赚到你人生的第一桶金? 零基础程序定制脚本开发课程,是完全针对零脚本开发经验的小白而设计,课程内容共分为3大阶段: ①前期将带你掌握Q开发语言和界面交互开发能力; ②中期通过实战来制作有具体需求的定制脚本; ③后期将解锁脚本的更高阶玩法,打通任督二脉; ④应用定制脚本合法赚取额外收入的完整经验分享,带你通过程序定制脚本开发这项副业,赚取到你的第一桶金!

MFC一站式终极全套课程包

该套餐共包含从C小白到C++到MFC的全部课程,整套学下来绝对成为一名C++大牛!!!

C++语言基础视频教程

C++语言基础视频培训课程:本课与主讲者在大学开出的程序设计课程直接对接,准确把握知识点,注重教学视频与实践体系的结合,帮助初学者有效学习。本教程详细介绍C++语言中的封装、数据隐藏、继承、多态的实现等入门知识;主要包括类的声明、对象定义、构造函数和析构函数、运算符重载、继承和派生、多态性实现等。 课程需要有C语言程序设计的基础(可以利用本人开出的《C语言与程序设计》系列课学习)。学习者能够通过实践的方式,学会利用C++语言解决问题,具备进一步学习利用C++开发应用程序的基础。

北京师范大学信息科学与技术学院笔试10复试真题

北京师范大学信息科学与技术学院笔试,可以更好的让你了解北师大该学院的复试内容,获得更好的成绩。

深度学习原理+项目实战+算法详解+主流框架(套餐)

深度学习系列课程从深度学习基础知识点开始讲解一步步进入神经网络的世界再到卷积和递归神经网络,详解各大经典网络架构。实战部分选择当下最火爆深度学习框架PyTorch与Tensorflow/Keras,全程实战演示框架核心使用与建模方法。项目实战部分选择计算机视觉与自然语言处理领域经典项目,从零开始详解算法原理,debug模式逐行代码解读。适合准备就业和转行的同学们加入学习! 建议按照下列课程顺序来进行学习 (1)掌握深度学习必备经典网络架构 (2)深度框架实战方法 (3)计算机视觉与自然语言处理项目实战。(按照课程排列顺序即可)

网络工程师小白入门--【思科CCNA、华为HCNA等网络工程师认证】

本课程适合CCNA或HCNA网络小白同志,高手请绕道,可以直接学习进价课程。通过本预科课程的学习,为学习网络工程师、思科CCNA、华为HCNA这些认证打下坚实的基础! 重要!思科认证2020年2月24日起,已启用新版认证和考试,包括题库都会更新,由于疫情原因,请关注官网和本地考点信息。题库网络上很容易下载到。

Python界面版学生管理系统

前不久上传了一个控制台版本的学生管理系统,这个是Python界面版学生管理系统,这个是使用pycharm开发的一个有界面的学生管理系统,基本的增删改查,里面又演示视频和完整代码,有需要的伙伴可以自行下

软件测试2小时入门

本课程内容系统、全面、简洁、通俗易懂,通过2个多小时的介绍,让大家对软件测试有个系统的理解和认识,具备基本的软件测试理论基础。 主要内容分为5个部分: 1 软件测试概述,了解测试是什么、测试的对象、原则、流程、方法、模型;&nbsp; 2.常用的黑盒测试用例设计方法及示例演示;&nbsp; 3 常用白盒测试用例设计方法及示例演示;&nbsp; 4.自动化测试优缺点、使用范围及示例‘;&nbsp; 5.测试经验谈。

Tomcat服务器下载、安装、配置环境变量教程(超详细)

未经我的允许,请不要转载我的文章,在此郑重声明!!! 请先配置安装好Java的环境,若没有安装,请参照我博客上的步骤进行安装! 安装Java环境教程https://blog.csdn.net/qq_40881680/article/details/83585542 Tomcat部署Web项目(一)·内嵌https://blog.csdn.net/qq_40881680/article/d...

2019数学建模A题高压油管的压力控制 省一论文即代码

2019数学建模A题高压油管的压力控制省一完整论文即详细C++和Matlab代码,希望对同学们有所帮助

图书管理系统(Java + Mysql)我的第一个完全自己做的实训项目

图书管理系统 Java + MySQL 完整实训代码,MVC三层架构组织,包含所有用到的图片资源以及数据库文件,大三上学期实训,注释很详细,按照阿里巴巴Java编程规范编写

linux下利用/proc进行进程树的打印

在linux下利用c语言实现的进程树的打印,主要通过/proc下的目录中的进程文件,获取status中的进程信息内容,然后利用递归实现进程树的打印

微信小程序开发实战之番茄时钟开发

微信小程序番茄时钟视频教程,本课程将带着各位学员开发一个小程序初级实战类项目,针对只看过官方文档而又无从下手的开发者来说,可以作为一个较好的练手项目,对于有小程序开发经验的开发者而言,可以更好加深对小程序各类组件和API 的理解,为更深层次高难度的项目做铺垫。

[已解决]踩过的坑之mysql连接报“Communications link failure”错误

目录 前言 第一种方法: 第二种方法 第三种方法(适用于项目和数据库在同一台服务器) 第四种方法 第五种方法(项目和数据库不在同一台服务器) 总结 前言 先给大家简述一下我的坑吧,(我用的是mysql,至于oracle有没有这样的问题,有心的小伙伴们可以测试一下哈), 在自己做个javaweb测试项目的时候,因为买的是云服务器,所以数据库连接的是用ip地址,用IDE开发好...

人工智能-计算机视觉实战之路(必备算法+深度学习+项目实战)

系列课程主要分为3大阶段:(1)首先掌握计算机视觉必备算法原理,结合Opencv进行学习与练手,通过实际视项目进行案例应用展示。(2)进军当下最火的深度学习进行视觉任务实战,掌握深度学习中必备算法原理与网络模型架构。(3)结合经典深度学习框架与实战项目进行实战,基于真实数据集展开业务分析与建模实战。整体风格通俗易懂,项目驱动学习与就业面试。 建议同学们按照下列顺序来进行学习:1.Python入门视频课程 2.Opencv计算机视觉实战(Python版) 3.深度学习框架-PyTorch实战/人工智能框架实战精讲:Keras项目 4.Python-深度学习-物体检测实战 5.后续实战课程按照自己喜好选择就可以

2019 AI开发者大会

2019 AI开发者大会(AI ProCon 2019)是由中国IT社区CSDN主办的AI技术与产业年度盛会。多年经验淬炼,如今蓄势待发:2019年9月6-7日,大会将有近百位中美顶尖AI专家、知名企业代表以及千余名AI开发者齐聚北京,进行技术解读和产业论证。我们不空谈口号,只谈技术,诚挚邀请AI业内人士一起共铸人工智能新篇章!

机器学习初学者必会的案例精讲

通过六个实际的编码项目,带领同学入门人工智能。这些项目涉及机器学习(回归,分类,聚类),深度学习(神经网络),底层数学算法,Weka数据挖掘,利用Git开源项目实战等。

Python数据分析师-实战系列

系列课程主要包括Python数据分析必备工具包,数据分析案例实战,核心算法实战与企业级数据分析与建模解决方案实战,建议大家按照系列课程阶段顺序进行学习。所有数据集均为企业收集的真实数据集,整体风格以实战为导向,通俗讲解Python数据分析核心技巧与实战解决方案。

YOLOv3目标检测实战系列课程

《YOLOv3目标检测实战系列课程》旨在帮助大家掌握YOLOv3目标检测的训练、原理、源码与网络模型改进方法。 本课程的YOLOv3使用原作darknet(c语言编写),在Ubuntu系统上做项目演示。 本系列课程包括三门课: (1)《YOLOv3目标检测实战:训练自己的数据集》 包括:安装darknet、给自己的数据集打标签、整理自己的数据集、修改配置文件、训练自己的数据集、测试训练出的网络模型、性能统计(mAP计算和画出PR曲线)和先验框聚类。 (2)《YOLOv3目标检测:原理与源码解析》讲解YOLOv1、YOLOv2、YOLOv3的原理、程序流程并解析各层的源码。 (3)《YOLOv3目标检测:网络模型改进方法》讲解YOLOv3的改进方法,包括改进1:不显示指定类别目标的方法 (增加功能) ;改进2:合并BN层到卷积层 (加快推理速度) ; 改进3:使用GIoU指标和损失函数 (提高检测精度) ;改进4:tiny YOLOv3 (简化网络模型)并介绍 AlexeyAB/darknet项目。

2021考研数学张宇基础30讲.pdf

张宇:博士,全国著名考研数学辅导专家,教育部“国家精品课程建设骨干教师”,全国畅销书《张宇高等数学18讲》《张宇线性代数9讲》《张宇概率论与数理统计9讲》《张宇考研数学题源探析经典1000题》《张宇考

三个项目玩转深度学习(附1G源码)

从事大数据与人工智能开发与实践约十年,钱老师亲自见证了大数据行业的发展与人工智能的从冷到热。事实证明,计算机技术的发展,算力突破,海量数据,机器人技术等,开启了第四次工业革命的序章。深度学习图像分类一直是人工智能的经典任务,是智慧零售、安防、无人驾驶等机器视觉应用领域的核心技术之一,掌握图像分类技术是机器视觉学习的重中之重。针对现有线上学习的特点与实际需求,我们开发了人工智能案例实战系列课程。打造:以项目案例实践为驱动的课程学习方式,覆盖了智能零售,智慧交通等常见领域,通过基础学习、项目案例实践、社群答疑,三维立体的方式,打造最好的学习效果。

DirectX修复工具V4.0增强版

DirectX修复工具(DirectX Repair)是一款系统级工具软件,简便易用。本程序为绿色版,无需安装,可直接运行。 本程序的主要功能是检测当前系统的DirectX状态,如果发现异常则进行修复

期末考试评分标准的数学模型

大学期末考试与高中的考试存在很大的不同之处,大学的期末考试成绩是主要分为两个部分:平时成绩和期末考试成绩。平时成绩和期末考试成绩总分一般为一百分,然而平时成绩与期末考试成绩所占的比例不同会导致出现不同

Vue.js 2.0之全家桶系列视频课程

基于新的Vue.js 2.3版本, 目前新全的Vue.js教学视频,让你少走弯路,直达技术前沿! 1. 包含Vue.js全家桶(vue.js、vue-router、axios、vuex、vue-cli、webpack、ElementUI等) 2. 采用笔记+代码案例的形式讲解,通俗易懂

c语言项目开发实例

十个c语言案例 (1)贪吃蛇 (2)五子棋游戏 (3)电话薄管理系统 (4)计算器 (5)万年历 (6)电子表 (7)客户端和服务器通信 (8)潜艇大战游戏 (9)鼠标器程序 (10)手机通讯录系统

相关热词 c# 不能序列化继承类 c# char* 调用 c# 开发dll模板 c#添加控件到工具箱 c#控制台组合数 编程计算猴子吃桃问题c# c# wpf 背景透明 随机抽取号码软件c# c# 开发环境 c# 属性和字段
立即提问