Why does instabot in flask throw an error about wsgi? - python

Hello when i try to post on instagram flask doesn't let me do it and i have no idea why. I tested the instagram bot's library and it works but in flask it doesn't want to. Can someone help me solve this problem?
Python gives me this error:
2021-09-11 12:23:38,852 - INFO - Instabot version: 0.117.0 Started
2021-09-11 12:23:38,853 - INFO - Not yet logged in starting: PRE-LOGIN FLOW!
2021-09-11 12:23:41,559 - INFO - Logged-in successfully as 'user'!
2021-09-11 12:23:41,559 - INFO - LOGIN FLOW! Just logged-in: True
127.0.0.1 - - [11/Sep/2021 12:23:53] "POST /submit HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Users\adamk\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 2088, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\adamk\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 2073, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\adamk\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\adamk\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\adamk\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\adamk\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "D:\Programowanie\spotted\app.py", line 43, in submit
bot.login(username="user", password="password")
File "C:\Users\adamk\AppData\Local\Programs\Python\Python39\Lib\site-packages\instabot\bot\bot.py", line 450, in login
signal.signal(signal.SIGTERM, self.print_counters)
File "C:\Users\adamk\AppData\Local\Programs\Python\Python39\Lib\signal.py", line 47, in signal
handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread of the main interpreter
127.0.0.1 - - [11/Sep/2021 12:23:53] "GET /submit?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [11/Sep/2021 12:23:53] "GET /submit?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [11/Sep/2021 12:23:54] "GET /submit?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [11/Sep/2021 12:23:54] "GET /submit?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
Here's my code:
#app.route('/submit', methods=['POST', 'GET'])
def submit():
if request.method == 'POST':
message = request.form['text']
message = message.replace('\r', '')
if message.rstrip() == '':
return render_template('index.html', message='You cannot send an empty message!')
font = ImageFont.truetype("OpenSans-Regular.ttf", 40)
img = Image.open('image.jpg')
draw = ImageDraw.Draw(img)
draw.text((170, 280), message.rstrip(), (0, 0, 0), font=font)
i = 0
while os.path.exists(f'image-output-{i}.jpeg'):
i += 1
img.save(f'image-output-{i}.jpg')
cookie_del = glob.glob("config/*cookie.json")
os.remove(cookie_del[0])
bot = Bot()
bot.login(username="user", password="password")
bot.upload_photo('image.jpg', caption='')
return render_template('sent.html')

This is not a problem with flask but rather instabot. You can see in the traceback:
File "D:\Programowanie\spotted\app.py", line 43, in submit
Which is the only part of the traceback that actually references your own code. The login method is here. From the docstring, you'll see:
if login function is run threaded, for example in scheduled job,
signal will fail because it 'only works in main thread'.
In this case, you may want to call login(is_threaded=True).
flask uses thread-local objects so you need to add the argument suggested.

Related

Flask unable to capture 404 errors, as for some reason it returns 500 error whilst attempting to handle

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [08/Apr/2021 10:38:05] "GET / HTTP/1.1" 200 -
[2021-04-08 10:38:08,866] ERROR in app: Exception on /cap [GET]
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 1926, in dispatch_request
self.raise_routing_exception(req)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 1908, in raise_routing_exception
raise request.routing_exception
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/ctx.py", line 350, in match_request
result = self.url_adapter.match(return_rule=True)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/werkzeug/routing.py", line 1945, in match
raise NotFound()
werkzeug.exceptions.NotFound: 404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 1816, in handle_user_exception
return self.handle_http_exception(e)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 1744, in handle_http_exception
return handler(e)
TypeError: not_found() takes 0 positional arguments but 1 was given
127.0.0.1 - - [08/Apr/2021 10:38:08] "GET /cap HTTP/1.1" 500 -
127.0.0.1 - - [08/Apr/2021 10:38:08] "GET /favicon.ico HTTP/1.1" 200 -
/cap is not a valid endpoint. When I Try to get it, it should surely return a error 404, as shown initially by the error message, and this block of code should work.
#app.errorhandler(404)
def page_not_found():
print('hit')
return '400'
However, for whatever reason, it does not, and a 500 arrises which I cannot catch with Flask. I just want to account for URLs that are not valid endpoints and redirect to the home page as a consequence, but it seems this is not working.
Any help is hugely appreciated.
a lackluster fix, however
#app.route('/', defaults={'path': ''})
#app.route('/<path:path>')
def catch_all(path):
print(f'recieved invalid request attempt of /{path}')
return render_template('redirect.html', reason='Unrecognised endpoint.')
does work using this app route as a 'catchall' to prevent any 404 errors in the first place.
A 404 error handler must be able to take some parameters.
#app.errorhandler(404)
def page_not_found(_):
print('hit')
return '400'
This should work..
#app.errorhandler(404)
def page_not_found(error):
return render_template('errorpage.html'), 404
Also,
app.register_error_handler(404, page_not_found)

Python DocuSign API receiving redirect URI error on the sample app

I am running the Python and React MyUni Education sample app and have it loading in my localhost3000. When I click on the logins though it is giving me redirect error.
I created a new Docusign integration key in case there was something incorrectly configured in my previous set up, but the error remains the same:
"The redirect URI is not registered properly with DocuSign" error
Docusign sandbox configured with:
Redirect URIs "http://localhost:5001/api"
.env file I believe has the right environment variables set but please let me know if I am missing anything.
# Configuration file for the example
DS_CLIENT_ID=blank
DS_CLIENT_SECRET=blank
DS_IMPERSONATED_USER_GUID=blank
DS_TARGET_ACCOUNT_ID=false
DS_PAYMENT_GATEWAY_ID=blank
DS_PAYMENT_GATEWAY_NAME=Stripe
DS_PAYMENT_GATEWAY_DISPLAY_NAME=Stripe
DS_PRIVATE_KEY=blank
# React environment variables
**REACT_APP_DS_RETURN_URL=http://localhost:3000
REACT_APP_API_BASE_URL=http://localhost:5001/api**
REACT_APP_DS_AUTH_SERVER=https://account-d.docusign.com
# Demo Docusign API URL
REACT_APP_DS_DEMO_SERVER=https://demo.docusign.net
REACT_APP_DS_CLICKWRAP_URL=//demo.docusign.net/clickapi/sdk/latest/docusign-click.js
I believe it is affecting the JWT, as when I selected the "continue with a preconfigured login" I received a "Request failed with status code 500" error as well. Logs from that below.
PS C:\Users\windowsuser\OneDrive\Documents\GitHub\sample-app-myuni> flask run --port 5001
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5001/ (Press CTRL+C to quit)
127.0.0.1 - - [27/Jul/2020 16:13:20] "GET /api/get_status HTTP/1.1" 200 -
127.0.0.1 - - [27/Jul/2020 16:13:51] "GET /api/code_grant_auth HTTP/1.1" 401 -
127.0.0.1 - - [27/Jul/2020 16:14:03] "OPTIONS /api/jwt_auth HTTP/1.1" 200 -
[2020-07-27 16:14:04,237] ERROR in app: Exception on /api/jwt_auth [POST]
Traceback (most recent call last):
File "c:\python38\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "c:\python38\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\python38\lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "c:\python38\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\python38\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "c:\python38\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "c:\python38\lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "c:\python38\lib\site-packages\flask_cors\decorator.py", line 128, in wrapped_function
resp = make_response(f(*args, **kwargs))
File "C:\Users\windowsuser\OneDrive\Documents\GitHub\sample-app-myuni\app\api\auth.py", line 43, in jwt_auth
DsClient.update_token()
File "C:\Users\windowsuser\OneDrive\Documents\GitHub\sample-app-myuni\app\ds_client.py", line 36, in update_token
client.request_jwt_user_token(DsConfig.client_id(),
File "c:\python38\lib\site-packages\docusign_esign\client\api_client.py", line 679, in request_jwt_user_token
raise ArgumentException("Private key not supplied or is invalid!")
File "c:\python38\lib\site-packages\docusign_esign\client\api_exception.py", line 51, in __init__
super(Exception).__init__(*args, **kwargs)
TypeError: super() argument 1 must be type, not str
127.0.0.1 - - [27/Jul/2020 16:14:04] "POST /api/jwt_auth HTTP/1.1" 500 -
127.0.0.1 - - [27/Jul/2020 16:18:14] "GET /api/code_grant_auth HTTP/1.1" 401 -
The integration key settings must match exactly
I think what you can check the URL where you get this error, it has first the IK which you created (GUID value starting with 61C9) then it has the redirectUri. It is URI encoded, but you can figure it out and make sure the same exact matching URI is set in the IK settings in the DocuSign Developer account.
I think it's the localhost:3000 for the front-end and not the localhost:5001 for the back-end and maybe there's an endpoint under there, just check and confirm and add it, wait 30 seconds and try again.
Okay just tested this in MySure app. Adding the following will allow the log in function to work as expected.
http://localhost:5001/api/callback
http://localhost:3000/callback
http://localhost:3000/

Hi, How can i sum all elements in sqlite database together to get the sum total of the number using Flask(python)

The model and view
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
class account (db.Model):
id = db.Column(db.Integer,primary_key=True)
amount = db.Column(db.BigInteger,default=0)
today=db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
#app.route('/office' , methods=['GET', 'POST'])
def office():
funds = account.query.all()
for fund in funds:
print (fund.amount)
This code ran well without error listing all the amount in the database but if i should add sum to the second code it gives error
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://localhost:7000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 263-984-974
5247065
5247065
5247065
5247065
127.0.0.1 - - [10/Feb/2020 16:02:59] "GET /office HTTP/1.1" 200 -
I'm trying to add all the list together to get the sum total output.
#app.route('/office' , methods=['GET', 'POST'])
def office():
funds = account.query.all()
for fund in funds:
print (sum(fund.amount))
it's giving error.
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://localhost:7000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 263-984-974
127.0.0.1 - - [10/Feb/2020 16:08:50] "GET /office HTTP/1.1" 500 -
Traceback (most recent call last):
File "/home/blazskills/.local/lib/python3.7/site-packages/flask/app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "/home/blazskills/.local/lib/python3.7/site-packages/flask/app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "/home/blazskills/.local/lib/python3.7/site-packages/flask/app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/blazskills/.local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/blazskills/.local/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/home/blazskills/.local/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/blazskills/.local/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/blazskills/.local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/blazskills/.local/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/home/blazskills/.local/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/blazskills/Documents/tacgwarimpalatest/app.py", line 205, in office
print (sum(fund.amount))
TypeError: 'int' object is not iterable
127.0.0.1 - - [10/Feb/2020 16:08:50] "GET /office?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [10/Feb/2020 16:08:50] "GET /office?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [10/Feb/2020 16:08:50] "GET /office?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [10/Feb/2020 16:08:50] "GET /office?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [10/Feb/2020 16:08:50] "GET /office?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
Try:
funds = account.query.all()
print(sum([fund.amount for fund in funds]))
Try doing this,
For example;
yourarray = [12, 3, 4, 15]
ans = sum(your array)
And ensure the value you are passing to the sum function is structured properly.
There are two ways to go around this;
Sum them all in your python code (you're using this) or sum them at the database level (performance smart, you should use this)
Method A. using your approach:
#app.route('/office' , methods=['GET', 'POST'])
def office():
accounts = account.query.all()
funds = [account.fund for account in accounts]
total_fund = sum(funds)
Method B. to sum them at the database level, add this to your model class:
from sqlalchemy import func
def total_funds(self):
return db.session.query(func.sum(account.amount))

No such file or directory" [Errno 2] No such file or directory with flask

I am learning Flask and am attempting to work through the uploading files.
I get the following [Errno 2] No such file or directory with flask.
see
How can I tell Flask to look in the right place?
See my app.html
from flask import render_template, jsonify, Flask, redirect, url_for, request
from app import app
import random
import os
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
#app.route('/')
#app.route('/index')
def index():
return render_template('index.html', title='Home')
#app.route('/upload.php', methods = ['GET', 'POST'])
def upload():
if request.method == 'POST':
f = request.files['file']
model= ResNet50(weights='imagenet')
img = image.load_img(f.filename)
preds = model.predict(img)
return render_template('uploaded.html', predictions=preds_decoded)
#app.route('/map')
def map():
return render_template('map.html', title='Map')
#app.route('/map/refresh', methods=['POST'])
def map_refresh():
points = [(random.uniform(48.8434100, 48.8634100),
random.uniform(2.3388000, 2.3588000))
for _ in range(random.randint(2, 9))]
return jsonify({'points': points})
#app.route('/contact')
def contact():
return render_template('contact.html', title='Contact')
I defined my UPLOADED_FOLDER in my config.py
/Users/name/Desktop/flaskSaaS-master/app/forms
my config.py
import logging
from app.config_common import *
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
app = Flask(__name__)
# the toolbar is only enabled in debug mode:
app.debug = True
# set a 'SECRET_KEY' to enable the Flask session cookies app.config['SECRET_KEY'] = 'houdini' app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False toolbar = DebugToolbarExtension(app)
# DEBUG can only be set to True in a development environment for security reasons DEBUG = True
# Secret key for generating tokens SECRET_KEY = 'houdini'
# Admin credentials ADMIN_CREDENTIALS = ('admin', 'pa$$word')
# Database choice SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db' SQLALCHEMY_TRACK_MODIFICATIONS = True
# Configuration of a Gmail account for sending mails MAIL_SERVER = 'smtp.googlemail.com' MAIL_PORT = 465 MAIL_USE_TLS = False MAIL_USE_SSL = True MAIL_USERNAME = 'flask.boilerplate' MAIL_PASSWORD
= 'flaskboilerplate123' ADMINS = ['flask.boilerplate#gmail.com']
# Number of times a password is hashed BCRYPT_LOG_ROUNDS = 12
LOG_LEVEL = logging.DEBUG LOG_FILENAME = 'activity.log' LOG_MAXBYTES = 1024 LOG_BACKUPS = 2
UPLOAD_FOLDER = '/Users/name/Desktop/flaskSaaS-master/app/forms'
Debug:
* Debugger is active!
* Debugger PIN: 127-013-508
127.0.0.1 - - [29/Sep/2019 20:48:36] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [29/Sep/2019 20:48:36] "GET /_debug_toolbar/static/css/toolbar.css?0.5076085944288159 HTTP/1.1" 200 -
127.0.0.1 - - [29/Sep/2019 20:49:04] "POST /upload.php HTTP/1.1" 500 -
Traceback (most recent call last):
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask_debugtoolbar/__init__.py", line 125, in dispatch_request
return view_func(**req.view_args)
File "/anaconda3/envs/tensorflow/lib/python3.6/cProfile.py", line 109, in runcall
return func(*args, **kw)
File "/Users/lorenzocastagno/Desktop/flaskSaaS-master/app/views/main.py", line 27, in upload
img = image.load_img(f.filename)
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras_preprocessing/image/utils.py", line 110, in load_img
img = pil_image.open(path)
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/PIL/Image.py", line 2770, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'mmm.jpg'
127.0.0.1 - - [29/Sep/2019 20:49:04] "GET /upload.php?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [29/Sep/2019 20:49:04] "GET /upload.php?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [29/Sep/2019 20:49:04] "GET /upload.php?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [29/Sep/2019 20:49:04] "GET /upload.php?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [29/Sep/2019 20:49:04] "GET /upload.php?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
The issue is with img = image.load_img(f.filename)
The load_img will try to read the file from the server. But in your case the file is not present in the file system of the server and is available in the request.files
In order to solve this, first you need to write the file present in request.files to some location and then use that location to load the file

Flask API not working, also unable to read csv by request.files.get

I new to creating rest apis for model deployment. I am trying to write a code to host an api from my system. I have read all relevant questions and tried different ways but none of them answer the problem I'm facing.
I have written the below code. But the API is not working.
app = Flask(__name__)
swagger = Swagger(app)
#def main():
#app.route('/',methods=['GET','POST'])
def predict_inv():
"""Example file endpoint
---
parameters:
- name: input_file
in: formData
type: file
required: true
"""
print("entry in to the job")
#dfinput = pd.read_csv(request.files.get("input_file"),encoding='cp1252')
#dfinput = pd.read_csv(request.files.get('uploaded_file'),encoding="utf8")
dfinput = pd.read_csv(request.files.get('file'))
print("entry")
PicklePath = "C:/Users/koyeli/data/gbsemail_adaV0.1.pkl"
model1 = joblib.load(PicklePath)
print("model loaded")
#FilePath1 = "C:/Users/z001133/Desktop/work files/customer quality/SAFETY/data/jan1st.csv"
dfclean = clean_data(dfinput['Body'])
filenm1 = "email_classification_ml_result"
predict(model1,filenm1,dfclean)
print("before return")
return 'OK'
if __name__ == '__main__':
app.run(debug=True, use_reloader=False)
Im getting the following error.
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [13/Aug/2019 09:43:44] "GET / HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "<ipython-input-77-0c3a1ef05475>", line 18, in predict_invoice
File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py", line 678, in parser_f
return _read(filepath_or_buffer, kwds)
File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py", line 424, in _read
filepath_or_buffer, encoding, compression)
File "C:\Users\z026355\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\common.py", line 218, in get_filepath_or_buffer
raise ValueError(msg.format(_type=type(filepath_or_buffer)))
ValueError: Invalid file path or buffer object type: <class 'NoneType'>
127.0.0.1 - - [13/Aug/2019 09:43:44] "GET /?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [13/Aug/2019 09:43:44] "GET /?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [13/Aug/2019 09:43:44] "GET /?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [13/Aug/2019 09:43:45] "GET /?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [13/Aug/2019 09:43:45] "GET /?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
entry in to the job
127.0.0.1 - - [13/Aug/2019 09:43:45] "GET /?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
It is printing "Entry to job" but api is not working.
Below is the error im getting in api.
builtins.ValueError
ValueError: Invalid file path or buffer object type: <class 'NoneType'>
Is there a problem for reading the csv file or is there something wrong with my approach in code. Please suggest.
You need csv reader for reading csv file
try like this
from flask import Flask, make_response, request
import io
import csv
app = Flask(__name__)
def transform(text_file_contents):
return text_file_contents.replace("=", ",")
#app.route('/')
def form():
return """
<html>
<body>
<h1>Transform a file demo</h1>
<form action="/transform" method="post" enctype="multipart/form-data">
<input type="file" name="data_file" />
<input type="submit" />
</form>
</body>
</html>
"""
#app.route('/transform', methods=["POST"])
def transform_view():
f = request.files['data_file']
if not f:
return "No file"
stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
csv_input = csv.reader(stream)
#print("file contents: ", file_contents)
#print(type(file_contents))
print(csv_input)
for row in csv_input:
print(row)
return 'OK'
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5001, debug=True)
Now check

Categories