SCENARIO
I am using a python flask server to serve up data from my remote database. I am tempting to use the requests framework to connect to my database with a held connection.
TECHNOLOGY USED
Python 3.10
Flask 2.0.3
Poetry 1.0 (for dependencies)
Requests 2.28.1 (added with Poetry)
IBM Code Engine (cloud platform/environment)
ISSUE
My project works just fine up until I add the line import request at the top of my server.py. When I add this line no responses are given by my server and it times out.
CODE
The below outputs { "hello": "there" }, because import requests was not added.
import os
import sys
import json
from collections import Counter
from flask import Flask, render_template, request, session, url_for, jsonify
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def main():
return { 'hello': "there" }
if __name__ == 'main':
app.run()
The below stalls and servers no response, because import requests was added.
import os
import sys
import json
import requests # adding this
from collections import Counter
from flask import Flask, render_template, request, session, url_for, jsonify
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def main():
return { 'hello': "there" }
if __name__ == 'main':
app.run()
QUESTION
Why can't I import requests, and if I'm missing something could you please leave a code answer as to what I need to do to get this working?
(I've noticed some other frameworks can't be imported either)
Related
I am using python 2.7 and flask that returns a complete response to my local setup. Now the application is dockerized the and deployed in Google kubernetes container. This is a sample API of POST method which takes inputs as application/json, currently the internal function able to fetch the data in JSON format but its not return to the client end.
Python part:
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS, cross_origin
import sys
from runmodel import run
reload(sys) # Reload is a hack
sys.setdefaultencoding('UTF8')
app = Flask(__name__, static_url_path='/static')
CORS(app)
#app.route("/modelrun", methods=['POST'])
def modelrun():
"""TO run the model and get data to populate"""
req_data = request.json
res = run(req_data) #another function return the data it will return json format
return jsonify(res)
My current problem is I am not getting the complete response, its return the ValueError: View function did not return a response// Werkzeug Debugger in the web browser.
Here are the logs and Traceback:
labels{
container.googleapis.com/stream: "stderr"
}
BrokenFilesystemWarning)
severity: "ERROR"
textPayload: " BrokenFilesystemWarning)
I am newbiee on pyhton development and trying to make the following example work.
The following code is for service authentication. Whenever I call localhost:3000/callback through browser, I am receiving code error because it is null.
When I create a webpage on auth0, then it puts all required information and then make the source code available to use. However, code is not included. I wonder what needs to inserted.
token = get_token.authorization_code(AUTH0_CLIENT_ID,
AUTH0_CLIENT_SECRET, code,
AUTH0_CALLBACK_URL)
auth0.v3.exceptions.Auth0Error: invalid_request: Missing required
parameter: code
.env
AUTH0_CLIENT_ID=xxxxxxxxxxx
AUTH0_DOMAIN=xxxxxx.auth0.com
AUTH0_CLIENT_SECRET=v-xxxxx2yVHntpn01RoEMMxhj6RLxxxxxxxxxx
AUTH0_CALLBACK_URL=http://localhost:3000/callback
API_IDENTIFIER={API_AUDIENCE}
server.py
"""Python Flask WebApp Auth0 integration example"""
from functools import wraps
from urllib.parse import urlparse
from os import environ as env, path
import json
from auth0.v3.authentication import GetToken
from auth0.v3.authentication import Users
from dotenv import load_dotenv
from flask import Flask
from flask import redirect
from flask import render_template
from flask import request
from flask import send_from_directory
from flask import session
import constants
load_dotenv(path.join(path.dirname(__file__), ".env"))
AUTH0_CALLBACK_URL = env[constants.AUTH0_CALLBACK_URL]
AUTH0_CLIENT_ID = env[constants.AUTH0_CLIENT_ID]
AUTH0_CLIENT_SECRET = env[constants.AUTH0_CLIENT_SECRET]
AUTH0_DOMAIN = env[constants.AUTH0_DOMAIN]
#APP.route('/callback')
def callback_handling():
code = request.args.get(constants.CODE_KEY)
get_token = GetToken(AUTH0_DOMAIN)
auth0_users = Users(AUTH0_DOMAIN)
#Receive exception
token = get_token.authorization_code(AUTH0_CLIENT_ID,
AUTH0_CLIENT_SECRET, code, AUTH0_CALLBACK_URL)
user_info = auth0_users.userinfo(token['access_token'])
session[constants.PROFILE_KEY] = json.loads(user_info)
return redirect('/dashboard')
if __name__ == "__main__":
APP.run(host='0.0.0.0', port=env.get('PORT', 3000))
I'm having a single test for retrieve documents in a single page, i know it's not correct to do in a single page; but it's just to understand all this work like pure script, not for an api restful.
My problem is when i use:
print (jsonify({'result' : output}))
i've get this error:
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
when I replace this line by
print ( output)
have no erros and have the documents.
How i can to specify a context for jsonify ? inside another context ? because i'm already using
with app.app_context():
Here the code:
from flask import Flask
from flask import g
from flask import jsonify
from flask import request
from flask_pymongo import PyMongo
from flask import make_response
from bson.objectid import ObjectId
from flask import current_app
import sys
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'restdb'
app.config['MONGO_URI'] = 'mongodb://localhost:27017/crm1'
#app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error':'Notfound' }),404)
with app.app_context():
mongo = PyMongo(app)
star = mongo.db.accounts
output = []
for s in star.find():
output.append({'id': str(s['_id']) ,'firstname' : s['firstname'], 'lastname' : s['lastname']})
print (jsonify({'result' : output}))
#print ( output)
if __name__ == '__main__':
app.run(debug=True)
Jsonify Works with HttpResponse.
You can use python json module and print the output
Like:
import json
print(json.dumps(output))
When I start the server, the console shows
python2 web.py
* Running on http://0.0.0.0:8005/ (Press CTRL+C to quit)
* Restarting with inotify reloader
And if I tried to make a request to the server, the flask server will be down.
I have no ideas what's wrong on it, it didn't throws any error log.
Here are what I imported
# -*- coding: utf8 -*-
from flask import request, url_for
from flask import json
from flask import Response
from flask import Flask, request, jsonify
from flask_request_params import bind_request_params
import datetime
import pandas as pd
import pymongo
import pdb
from webargs import Arg
from webargs.flaskparser import use_args, use_kwargs
import urlparse
from mongo import Mongo
import yaml
import time, functools
from functools import wraps
from pdb import set_trace
from flask import g
from pandas_helper import PandasHelper
inotify seems to be coming from Werkzeug, but I can't find anything suggesting that it should be using 0.0.0.0- this only appears with the inbuilt development server run function.
For development work werkzeug suggests:
from werkzeug.wrappers import Request, Response
#Request.application
def application(request):
return Response('Hello World!')
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('localhost', 4000, application)
Following some advice that I found here I am trying to use Flask as a web interface for an application that runs with twisted.
As suggested in Flask documentation I created a "templates" directory which is at the same level as my script but when I launch the server I get the following error:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
When I do not try to load a template and just write a string in the request it works fine. This is what makes me think it is related to the load of the template.
from twisted.internet import reactor
from twisted.web.resource import Resource
from twisted.web.wsgi import WSGIResource
from twisted.internet.threads import deferToThread
from twisted.web.server import Site, NOT_DONE_YET
from flask import Flask, request, session, redirect, url_for, abort, \
render_template, flash
app= Flask(__name__)
app.config.from_object(__name__)
#app.route('/login', methods= ['GET', 'POST'])
def login():
return render_template('login.html', error= error)
if __name__ == '__main__':
root = WSGIResource(reactor, reactor.getThreadPool(), app)
factory = Site(root)
reactor.listenTCP(8880, factory)
reactor.run()
Some frameworks will change directory from your current working directory when they are run in daemon mode, and this might very well be the case here.
Flask, since 0.7, has supported passing a template_folder keyword argument when calling Flask, so you could try:
import os
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
The following is a shorter version that will work just fine:
tmpl_dir = os.path.join(os.path.dirname(__file__), 'templates)
# ...
app = Flask('myapp', template_folder=tmpl_dir)
You can feed Jinja2 with a default templates directory (as written here) like this :
import jinja2
app = Flask(__name__)
app.jinja_loader = jinja2.FileSystemLoader('path/to/templates/directory')