I have a python script that I start from flask:
from flask import Flask, render_template, request, redirect, url_for
from transcode_audio_manual_stag_funct import get_epguid
application = Flask(__name__)
#application.route('/audiotranscode')
def homepage():
html = render_template('homepage.html')
return html
#application.route('/transcode', methods=['GET','POST'])
def transcode():
dmguid = request.form['mediaid']
get_epguid(dmguid)
return redirect(url_for('homepage'))
if __name__ == '__main__':
application.run(host='0.0.0.0')
At the end of the script, the status can be failed or successful.
...
def register_lowres_depot(dmguid, url_register_audio):
r = safegeturl(url_register_audio)
root = ET.fromstring(r.content)
jobID = root.text
status = ''
while not (status == '2' or status == '4'):
url_status = url %jobID
r = safegeturl(url_status)
root = ET.fromstring(r.content)
status = root.text
print(dmguid, status)
time.sleep(10)
if status == '2':
logger.info('{} successfully registered in depot'.format(dmguid))
else:
logger.warning('Failed to register audio lowres for {}'.format(dmguid))
if __name__ == '__main__':
get_epguid(dmguid)
How can I return that status back to my flask script and present it to the user?
You can make use of make_resopnse() method. What ever you need to present it to user, pass it as parameter to this method. Like below:
# case : Successful
resp = make_resopnse('{} successfully registered in depot'.format(dmguid))
resp.status_code = 200
return resp
# case : Failure
resp = make_resopnse('Failed to register audio lowres for {}'.format(dmguid))
resp.status_code = 500
return resp
Note : The above is very generic.
Related
Here I am attaching my server.py and util.py
I have trained a model, and now wish to print the data on user's demand.
server.py
from flask import Flask, request, jsonify
#from waitress import serve
import util
import json
#%run util.ipynb
app = Flask(__name__)
#app.route('/hi')
def hi():
return util.areas()
#app.route('/locations')
def locations():
response = jsonify({
'locations': util.locations()
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
#app.route('/predict_home_price', methods=['GET', 'POST'])
def predict_home_price():
total_sqft = float(request.form['total_sqft'])
location = request.form['location']
size = int(request.form['size'])
bath = int(request.form['bath'])
area_type = request.form['area_type']
balcony = int(request.form['balcony'])
response = jsonify({
'estimated_price': util.get_estimated_price(area_type, location, size, total_sqft, bath, balcony)
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
if __name__ == '__main__':
print('python flask started')
app.run()
#serve(app, host='0.0.0.0', port=50100, threads=1)
util.py
import json
import joblib
import numpy as np
__locations = None
__area = None
__model = None
def get_estimated_price(area_type, location, size, total_sqft, bath, balcony):
x = np.zeros(6)
x[0] = __area.index(area_type)
x[1] = __locations.index(location)
x[2] = size
x[3] = total_sqft
x[4] = bath
x[5] = balcony
return round(__model.predict([x])[0][0],2)
def locations():
return __locations
def areas():
return __area
def load_saved_artifacts():
print("loading saved artifacts...start")
global __data_columns
global __locations
global __area
with open('./artifacts/locations.json','r') as f:
__locations = json.load(f)['data_locations']
with open('./artifacts/area.json','r') as f:
__area = json.load(f)['data_area']
global __model
__model = joblib.load('./artifacts/Banglore_Real_State_Price')
print(" loading artifacts is done")
if __name__ == '__main__':
load_saved_artifacts()
#print(locations())
#print(areas())
print(get_estimated_price('Super built-up Area','Electronic City Phase II',2,1056,2,1))
print(get_estimated_price('Built-up Area','Uttarahalli',3,1440,2,3))
print(get_estimated_price('Super built-up Area','Lingadheeranahalli',3,1521,3,1))
print(get_estimated_price('Super built-up Area','Kothanur',2,1200,2,1))
Immediate help is really appreciated
I have trained a model, and now wish to print the data on user's demand.
I am seeing this error in server.py file, " The browser (or proxy) sent a request that this server could not understand." I checked everything works fine if I am sending data to browser but not when asking for the data, I tried Postman for sending the data.
http://127.0.0.1:5000/predict_home_price -> shows bad request.
http://127.0.0.1:5000/locations -> shows correct data
http://127.0.0.1:5000/hi -> shows correct data
As you mentioned, when you're sending data to the server it works, and that's because you're using a POST request and the request has form data in it.
But when you're "asking for data", you're probably using a GET request, which has no form data in it, and that's why the server responses with an error.
You can modify your code so you can decide what you should do for each type of request:
#app.route('/predict_home_price', methods=['GET', 'POST'])
def predict_home_price():
if request.method == "POST":
# get form data and do something with it
elif request.method == "GET":
# return some value, without looking for form data
I have created a get function in my flask application which looks something similar below.
flask_app.py
_cloudenv='dev.net'
app = Flask(__name__)
csrf = CSRFProtect()
csrf.init_app(app)
#app.route('/')
#app.route('/index')
def index():
project = "Project 1"
framework = "Publish Framework"
version = '0.1'
# May require to change
hostname = 'farid.net'
# return render_template('index.html', title=project , description=f'{project} : {framework} v - {version}' , hostname=hostname , get_env=_cloudenv)
test_flask.py
import flask_app as flk_app
from flask_app import app
class test_tbrp_case(unittest.TestCase):
def test_home_page_getenv(self):
response = app.test_client().get('/')
assert response.status_code == 200
assert response.get_env == 'dev.net'
def test_home_page_gettitle(self):
response = app.test_client().get('/')
assert response.status_code == 200
assert response.title== 'Project 1'
when i run my test cases , it failed, anything that i did wrong here ?
I am using python and I apologize as this is probably a very simple concept that I am not grasping but I am not very familiar with the flask framework. Right now I'm making a server with flask but run into a 405 error every time I try to do something with the twitter api shortly after. Right now my code looks something like this
In a separate file:
from flask import Flask
from threading import Thread
app = Flask('')
#app.route('/', methods=['GET', 'POST', 'DELETE'])
def home():
return "Hello world!"
def run():
app.run(host='0.0.0.0',port=8080)
app.run(debug=True, host="0.0.0.0")
def keep_alive():
t = Thread(target=run)
t.start()
Then I call my code in the main file:
from flaskfile import flask_file
flask_file()
MEDIA_ENDPOINT_URL = 'https://upload.twitter.com/1.1/media/upload.json'
POST_TWEET_URL = 'https://api.twitter.com/1.1/statuses/update.json'
CONSUMER_KEY = consumerkey
CONSUMER_SECRET = secret
ACCESS_TOKEN = accesstoken
ACCESS_TOKEN_SECRET = tokensecret
#fileName = check_and_download()
VIDEO_FILENAME = (filename)
oauth = OAuth1(CONSUMER_KEY,
client_secret=CONSUMER_SECRET,
resource_owner_key=ACCESS_TOKEN,
resource_owner_secret=ACCESS_TOKEN_SECRET)
class VideoTweet(object):
def __init__(self, file_name):
'''
Defines video tweet properties
'''
self.video_filename = file_name
self.total_bytes = os.path.getsize(self.video_filename)
self.media_id = None
self.processing_info = None
def upload_init(self):
'''
Initializes Upload
'''
print('INIT')
request_data = {
'command': 'INIT',
'media_type': 'video/mp4',
'total_bytes': self.total_bytes,
'media_category': 'tweet_video'
}
req = requests.post(url=MEDIA_ENDPOINT_URL, data=request_data, auth=oauth)
media_id = req.json()['media_id']
self.media_id = media_id
print('Media ID: %s' % str(media_id))
def upload_append(self):
'''
Uploads media in chunks and appends to chunks uploaded
'''
segment_id = 0
bytes_sent = 0
file = open(self.video_filename, 'rb')
while bytes_sent < self.total_bytes:
chunk = file.read(4*1024*1024)
print('APPEND')
request_data = {
'command': 'APPEND',
'media_id': self.media_id,
'segment_index': segment_id
}
files = {
'media':chunk
}
req = requests.post(url=MEDIA_ENDPOINT_URL, data=request_data, files=files, auth=oauth)
if req.status_code < 200 or req.status_code > 299:
print(req.status_code)
print(req.text)
sys.exit(0)
segment_id = segment_id + 1
bytes_sent = file.tell()
print('%s of %s bytes uploaded' % (str(bytes_sent), str(self.total_bytes)))
print('Upload chunks complete.')
def upload_finalize(self):
'''
Finalizes uploads and starts video processing
'''
print('FINALIZE')
request_data = {
'command': 'FINALIZE',
'media_id': self.media_id
}
req = requests.post(url=MEDIA_ENDPOINT_URL, data=request_data, auth=oauth)
print(req.json())
self.processing_info = req.json().get('processing_info', None)
self.check_status()
def check_status(self):
'''
Checks video processing status
'''
if self.processing_info is None:
return
state = self.processing_info['state']
print('Media processing status is %s ' % state)
if state == u'succeeded':
return
if state == u'failed':
sys.exit(0)
check_after_secs = self.processing_info['check_after_secs']
print('Checking after %s seconds' % str(check_after_secs))
time.sleep(check_after_secs)
print('STATUS')
request_params = {
'command': 'STATUS',
'media_id': self.media_id
}
req = requests.get(url=MEDIA_ENDPOINT_URL, params=request_params, auth=oauth)
self.processing_info = req.json().get('processing_info', None)
self.check_status()
def tweet(self):
'''
Publishes Tweet with attached video
'''
request_data = {
#leave status blank
'status': '',
'media_ids': self.media_id
}
req = requests.post(url=POST_TWEET_URL, data=request_data, auth=oauth)
print(req.json())
if __name__ == '__main__':
videoTweet = VideoTweet(VIDEO_FILENAME)
videoTweet.upload_init()
videoTweet.upload_append()
videoTweet.upload_finalize()
videoTweet.tweet()
The error returned states the following:
"Error response
Error code: 405
Message: Method Not Allowed.
Error code explanation: 405 - Specified method is invalid for this resource."
Basically I call the flask file then use twitter api to upload a file, but for some reason using the twitter api always results in a 405 error and my flask server is no longer accessible. How can I adjust my flask file to allow me to upload using the api?
405 errors are thrown when the wrong request method is used. For example a POST request being sent when a GET request was expected, or a GET request being sent when a POST request was expected.
In your check_status function you have
req = requests.get(url=MEDIA_ENDPOINT_URL, ...
But according to Twitter's documentation you should be using a post request here
req = requests.post(url=MEDIA_ENDPOINT_URL, ...
Using the following code, I've setup a flask app:
https://gist.github.com/ugik/a218a599b1af0ea06b1b38e3a5132078#file-flaskfbmapi-ai-rig
import requests
import json
from flask import Flask, request
import apiai
# FB messenger credentials
ACCESS_TOKEN = "EAAKsKOJ37rUBAKVZAQ21bn...UsZCXx6UWqQ6XuQr7OHnBYL3xD3Sy5u1ZAZCwip0XnTAHq25CsIpxRsbxZALRHOOguKm2unY7I06LRAZDZD"
# api.ai credentials
CLIENT_ACCESS_TOKEN = "78c0e0...d9404a2"
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
app = Flask(__name__)
#app.route('/', methods=['GET'])
def verify():
# our endpoint echos back the 'hub.challenge' value specified when we setup the webhook
if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
if not request.args.get("hub.verify_token") == 'foo':
return "Verification token mismatch", 403
return request.args["hub.challenge"], 200
return 'Hello World (from Flask!)', 200
def reply(user_id, msg):
data = {
"recipient": {"id": user_id},
"message": {"text": msg}
}
resp = requests.post("https://graph.facebook.com/v2.6/me/messages?access_token=" + ACCESS_TOKEN, json=data)
print(resp.content)
#app.route('/', methods=['POST'])
def handle_incoming_messages():
data = request.json
sender = data['entry'][0]['messaging'][0]['sender']['id']
message = data['entry'][0]['messaging'][0]['message']['text']
# prepare API.ai request
req = ai.text_request()
req.lang = 'en' # optional, default value equal 'en'
req.query = message
# get response from API.ai
api_response = req.getresponse()
responsestr = api_response.read().decode('utf-8')
response_obj = json.loads(responsestr)
if 'result' in response_obj:
response = response_obj["result"]["fulfillment"]["speech"]
reply(sender, response)
return "ok"
if __name__ == '__main__':
app.run(debug=True)
However, at line 51 there is an error in my server logs:
UnboundLocalError: local variable 'response' referenced before
assignment
Which I understand the root of the cause is "response" is defined only within the if statement, however, since it is not my code, I'm having trouble defining the variable outside. Will this work if I place this code after line 48:
response = response_obj["result"]["fulfillment"]["speech"]
I'm trying to authorize my application with twitter login authentication but after login into Twitter, It is not redirecting into my main page. It shows error:
SCREENSHOT
Here is my source code:
from flask import Flask
from flask import g, session, request, url_for, flash
from flask import redirect, render_template
from flask_oauth import OAuth
app = Flask(__name__)
app.debug = True
app.secret_key = 'development'
oauth = OAuth()
# Use Twitter as example remote application
twitter = oauth.remote_app('twitter',
base_url='https://api.twitter.com/1/',
request_token_url='https://api.twitter.com/oauth/request_token',
access_token_url='https://api.twitter.com/oauth/access_token',
authorize_url='https://api.twitter.com/oauth/authorize',
consumer_key='xxxxxxx',
consumer_secret='xxxxxxx'
)
#twitter.tokengetter
def get_twitter_token():
if 'twitter_oauth' in session:
resp = session['twitter_oauth']
return resp['oauth_token'], resp['oauth_token_secret']
#app.before_request
def before_request():
g.user = None
if 'twitter_oauth' in session:
g.user = session['twitter_oauth']
#app.route('/')
def index():
tweets = None
if g.user is not None:
resp = twitter.request('statuses/home_timeline.json')
if resp.status == 200:
tweets = resp.data
else:
flash('Unable to load tweets from Twitter.')
return render_template('index.html', tweets=tweets)
#app.route('/tweet', methods=['POST'])
def tweet():
if g.user is None:
return redirect(url_for('login', next=request.url))
status = request.form['tweet']
if not status:
return redirect(url_for('index'))
resp = twitter.post('statuses/update.json', data={
'status': status
})
if resp.status == 403:
flash('Your tweet was too long.')
elif resp.status == 401:
flash('Authorization error with Twitter.')
else:
flash('Successfully tweeted your tweet (ID: #%s)' % resp.data['id'])
return redirect(url_for('index'))
#app.route('/login')
def login():
callback_url = url_for('oauthorized', next=request.args.get('next'))
return twitter.authorize(callback=callback_url or request.referrer or None)
#app.route('/logout')
def logout():
session.pop('twitter_oauth', None)
return redirect(url_for('index'))
#app.route('/oauthorized')
def oauthorized():
resp = twitter.authorized_response()
if resp is None:
flash('You denied the request to sign in.')
else:
session['twitter_oauth'] = resp
return redirect(url_for('index'))
if __name__ == '__main__':
app.run()
PLEASE HELP ME...
ANY KIND OF HELP WOULD BE APPRECIATED!!
in your oauthorized function remove resp = twitter.authorized_response() statement and add a resp parameter to the function. it would be something like this:
#app.route('/oauthorized')
#twitter.authorized_response
def oauthorized(resp):
if resp is None:
flash('You denied the request to sign in.')
else:
session['twitter_oauth'] = resp
return redirect(url_for('index'))