I have a problem with python code in Openshift.
I have a subdomain on my app where I have to open a txt file with json format.
from flask import Flask
from flask import render_template
import json
app = Flask(__name__)
#app.route("/")
def index():
return render_template("home.html")
#app.route('/casestudy1')
def cs1():
json_data = open("cs1.txt")
data = json.load(json_data)
....do my staff....
return render_template("cs1.html")
if I remove the first two lines from cs1() the app works perfect. I tried to run flask localy from command line and it works there as well. The cs1.txt file is in the same root with the main.py.
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.
Error on log:
json_data = open("cs1.txt")
IOERROR: [Errno2] No such file or directory: cs1.txt
Application root:
-wsgi
-static
-css
-js
-templates
-cs1.html
-main.py
-cs1.txt
I found the problem.
import os
json_data = open(os.path.join(os.path.dirname(__file__),"cs1.txt"),'r')
instead of
json_data = open("cs1.txt")
Related
I am trying to get my Flask application to work with WSGI under Apache on RHEL 8. A flat file with no imports works fine, and the development server works fine, but WSGI returns module not found errors. This is my file strucuture:
/var/www/FLASKAPPS/myapp/
utility/
configuration.py
logging.py
__init__.py
Contents of init.py:
from flask import Flask, Response, request, abort
from flask_restful import Resource, Api, reqparse, inputs
from utility.configuration import Configuration
from utility.logger import Logger
app = Flask(__name__)
api = Api(app)
configuration = Configuration()
logger = Logger()
class Main(Resource):
#staticmethod
def get():
return {'message': 'Hello World.'}
api.add_resource(Main, '/')
if __name__ == "__main__":
app.run()
Running the Python test server works fine.
Accessing the server via WSGI on Apache gives the error:
File "/var/www/FLASKAPPS/myapp/__init__.py", line 6, in <module>
from utility.configuration import Configuration
No module named 'utility'
What do I need to do for WSGI to be able to see these modules?
Usecase: I have a python flask app that runs background_function() before serving any requests on routes.
When I execute the flask app, I receive the error - RuntimeError: Working outside of application context. I receive the error since I try to get the application context before any request is served.
What is the best pythonic way to execute the background_function() in this example?
from flask import Flask
from download import Download
app = Flask(__name__)
app.config.from_pyfile('config.py')
# run backgroung function
Download.background_function()
#app.route('/')
def index():
return 'Welcome!'
if __name__ == '__main__':
app.run()
The config file
FILE_LOCATION = os.environ['FILE_LOCATION'] # "file/path/on/server"
# Many other variables are present in this file
The download file
from flask import current_app as app
class Download:
#staticmethod
def background_function():
file_path = app.config["FILE_LOCATION"]
# code to download file from server to local
return
Try this:
from flask import Flask
from download import Download
app = Flask(__name__)
#app.route('/')
def index():
return 'Welcome!'
if __name__ == '__main__':
Download.background_function()
app.run()
the download file
from flask import current_app as app
class Download:
#staticmethod
def background_function():
print("testing")
given output:
testing
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
As you can see, the function runs first and prints testing and then runs the application.
trying to host my flask app (run.py) on PythonAnywhere. Have my virtualenv setup and all of my modules imported via pip. The flask app is stored at this location:
/home/goldsilvermonitor/GSM/run.py
Set up my WSGI file and it keeps giving my the error:
TypeError: 'module' object is not callable
My flask file look like this: (run.py)
from flask import Flask, flash, redirect, render_template, request, session, abort, url_for
app = Flask(__name__)
# ./Home Script:
#app.route("/")
#app.route("/index")
def index():
return render_template('index.html')
# ./Disclaimer Page:
#app.route("/disclaimer")
def disclaimer():
return render_template('disclaimer.html')
# ./data.xml:
app.route("/dataxml")
def dataxml():
return render_template('data.xml')
# ./404 Page
#app.errorhandler(404)
def page_not_found(e):
# 404 status set explicitly
return render_template('404.html'), 404
# FLask Debug Script:s
if __name__ == "__main__":
app.run(host="0.0.0.0", port='5000', debug=True)
And my WSGI file looks like this:
# +++++++++++ FLASK +++++++++++
# Flask works like any other WSGI-compatible framework, we just need
# to import the application. Often Flask apps are called "app" so we
# may need to rename it during the import:
#
#
import sys
#
## The "/home/goldsilvermonitor" below specifies your home
## directory -- the rest should be the directory you uploaded your Flask
## code to underneath the home directory. So if you just ran
## "git clone git#github.com/myusername/myproject.git"
## ...or uploaded files to the directory "myproject", then you should
## specify "/home/goldsilvermonitor/myproject"
path = '/home/goldsilvermonitor/GSM'
if path not in sys.path:
sys.path.append(path)
#
import run as application # noqa
#
# NB -- many Flask guides suggest you use a file called run.py; that's
# not necessary on PythonAnywhere. And you should make sure your code
# does *not* invoke the flask development server with app.run(), as it
# will prevent your wsgi file from working.
I have no idea what is causing this error. Have tried reuploading the files, redoing the WSGI config. But to no avail. If someone could help me then that would be great! Also should I remove the debug=true from the flask file before I go live?
You're trying to import a module (the file run.py) and then use it as an application; the application is the app object in that file, so in the WSGI file you should replace this:
import run as application # noqa
...with this:
from run import app as application # noqa
I have created a flask api and it is currently running in local machine
From one machine I ran the python script to post the text file:
import json
import requests
datas = {'var1' : 'var1','var2' : 'var2',}
#my file to be sent
local_file_to_send = 'C:\\Users\\tmp.txt'
with open(local_file_to_send, 'w') as f:
f.write('I am a file\n')
url = "http://127.0.0.1:5000/customerupdate"
files = [
('document', (local_file_to_send, open(local_file_to_send, 'rb'), 'application/octet')),
('datas', ('datas', json.dumps(datas), 'application/json')),
]
r = requests.post(url, files=files)
print("sd")
print(str(r.content, 'utf-8'))
Python flask API:
import json
from flask import Flask, request
from flask import send_file
app = Flask(__name__)
#app.route('/',methods=['GET'])
def hello_world():
return 'Hello World!'
#app.route('/customerupdate',methods=['GET','POST'])
def customerupdate():
posted_file = str(request.files['document'].read(), 'utf-8')
posted_data = json.load(request.files['datas'])
print(posted_file)
print(posted_data)
return '{}\n{}\n'.format(posted_file, posted_data)
if __name__=='__main__':
app.run(debug='true',threaded=True)
And the python get method to receive the file:
import requests
r = requests.get('http://127.0.0.1:5000')
print(r.text)
But here in get method I have received the contents of the file.But I want it for csv file.I tried by making that .csv instead of .txt.But can't able to send the file to api .So, Is it possible to send the csv file from one machine and receive the csv file in another machine via flask and please post the code if solutions available.
Already tried with this link:Python Flask: Send file and variable
I struggling lot to resolve it.
This question already has answers here:
How to upload file with python requests?
(9 answers)
Closed 4 years ago.
I was trying to create a minimal flask server/client python movie file uploader but my client-code doesn't seem to be working properly and I'm wondering if I need more then what I have?
Server.py
from flask import Flask, request
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST', 'PUT'])
def hello_world():
file = request.files
return(str(file))
running as: flask run
Uploader.py
import requests
files = {'file': open("BigBuckBunny_320x180.mp4")}
r = requests.post("http://127.0.0.1:5000/", files)
print(r.text)
running as: python Uploader.py
However the hello_world method returns ImmutableMultiDict([])
For Debugging purposes I've used this following curl snippet which seems to work:
curl -i -X PUT -F filedata=#BigBuckBunny_320x180.mp4 "http://localhost:5000/"
and returns
ImmutableMultiDict([('file', <FileStorage: u'BigBuckBunny_320x180.mp4' ('application/octet-stream')>)])
Any Idea why the Uploader.py fails?
I tried example you gave us and I think I managed to find a solution.
After some digging, I found that you can stream requests with requests module:
Requests supports streaming uploads, which allow you to send large streams or files without reading them into memory.
You just need to provide a file to be streamed and open it in read binary mode, rb.
app.py
from flask import Flask, request
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST', 'PUT'])
def hello_world():
# 'bw' is write binary mode
with open("BigBuckBunny_320x180_flask_upload.mp4", "bw") as f:
chunk_size = 4096
while True:
chunk = request.stream.read(chunk_size)
if len(chunk) == 0:
return 'Done'
f.write(chunk)
if __name__ == '__main__':
app.run()
Uploader.py
import requests
# Give proper path to your file, I used mine from flask app directory
with open('BigBuckBunny_320x180.mp4', 'rb') as f:
requests.post('http://127.0.0.1:5000/', data=f)
Check this article.