Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to create a simple api rest in python using flask and sqlalchemy. I install both successfully. I also install postman to test the code. I make a simple script in python in order to check if localhost is running. The code is this one:
from flask import Flask,request,jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
#init app
app = Flask(__name__)
#app.route('/',methods=['GET'])
def get():
return jsonfy({'msg': 'Server running'})
#run server
if __name__ == '__main__':
app.run(debug=True)
In postman I type the following url in the request: localhost:5000.
After send the request I watch the following messages:
Could not get any response
There was an error connecting to http:localhost:5000.
I type this url in a web browser and the message is the same.
I know the error is due to I haven't the server up. How can I do it?
Thanks.
have you configured flask?
if not, click cntrl + shift + a
=> then go to edit configuration and set flask to run when started.
it will suppose to let you after that to run it. (just assume you not running)
configuration seems to be okay but didn't tested.
look at the picture for the flask server (you probably don't have it so add it at the plus
use:
return jsonify({'msg': 'Server running'})
instead of:
return jsonfy({'msg': 'Server running'})
This one is working
from flask import Flask,request,jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
#init app
app = Flask(__name__)
#app.route('/',methods=['GET'])
def get():
return jsonify({'msg': 'Server running'})
if __name__ == '__main__':
app.run(debug=True)
it's showing this in Postman
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
when opening http://127.0.0.1:5000 on in my browser, i got following error. I tried to find the error online but nothing helped. i have following server 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.
from flask import Flask
app = Flask(__name__)
from flask import jsonify
import random
#app.route('/')
def Calutlate():
arr = []
for i in range(10):
n = random.randint(-10,35)
arr.append(n)
som = 0
for item in arr:
som += item
avg = som / 10
return jsonify(avg)
if __name__ == '__main__':
app.debug = True
app.run()
I think the problem is around your return function jsonify.
jsonify serializes data to JavaScript Object Notation (JSON) format, wraps it in a Response object with the application/json mimetype.
You actually don't give it a json format string which may create a potential problem.
I recommend you just to make a simple return statement like:
return avg
This question already has answers here:
How to run a flask application?
(6 answers)
Closed 2 years ago.
I am following the flask quickstart to create a python server so that I can send data from postman to the server. However, when I run the code using "python main.py", nothing happens in the command line. What am I doing wrong?
Code:
from flask import Flask, request
from flask_restful import Resource, Api
from server import analyzeWeaknesses
app = Flask(__name__)
api = Api(app)
#app.route('/analyzeWeaknesses', methods=['POST'])
def WeaknessAnalysis():
if request.method == 'POST':
analyzeWeaknesses(request.data)
return {"status":"success"}
else:
error = 'Unable to access data!'
analyzeWeaknesses simply takes in an input and does an analysis of it and outputs integers. I would like this output to be also returned to postman. Desired outcome Postman to for python input and then receive its output
You're missing the main function. Add this at the bottom of your code-
if __name__ == '__main__':
app.run()
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I have made an API app using flask, that takes a number(decimal) as input and returns some string. This app breaks if I send a string and works fine after re-starting it. I don't want to restart every time some error happens during processing. How do i do this?
Here is my code:
from flask import Flask, request, jsonify
# initiating the app
flask_api_app = Flask(__name__)
# the app accepts requests via "GET" and "POST" methods
#flask_api_app.route("/", methods=["GET", "POST"])
def output_risk_and_report():
# getting json data from api call
json_data = request.get_json(force=True)
# now the processing part
if json_data['number'] < 2:
return jsonify(["the number is less than two"])
else:
return jsonify(["the number is not less than two"])
# main function, in which app will be run
if __name__ == "__main__":
# running the app on local host
flask_api_app.run(debug=True, host='127.0.0.1', port='8080')
example of call which doesn't break the app: {"number":4}
example of call which breaks the app: {"number":"adfa"}
What changes do I make in my code to accomplish this?
EDIT 1:
i was naive to give that example in my question. in my original program, i may get an error when inserting data into database or may get an error with some arithmetic calculation or something. So, is there any way to tell flask to keep serving for new api requests and not break when an error occurs with only one api call.
When looking into the documents we can find this behaviour:
handle_exception(e)
Handle an exception that did not have an error handler associated with it, or that was raised from an error handler.
This always causes a 500 InternalServerError.
Always sends the got_request_exception signal.
If propagate_exceptions is True, such as in debug mode, the error will
be re-raised so that the debugger can display it. Otherwise, the
original exception is logged, and an InternalServerError is returned.
If an error handler is registered for InternalServerError or 500, it
will be used. For consistency, the handler will always receive the
InternalServerError. The original unhandled exception is available as
e.original_exception.
A way to catch this errors and do something with it could be this:
#app.errorhandler(Exception)
def handle_exception(e):
# pass through HTTP errors
if isinstance(e, HTTPException):
return e
# now you're handling non-HTTP exceptions only
return render_template("500_generic.html", e=e), 500
Source and extra documentation if needed you can find here:
Flask pallets projects
You need to trigger a return with an error message, if whatever the user submits can't be expressed as an integer.
The following should work for submissions like 3 and '3'
# now the processing part
try:
number = int(json_data['number'])
except ValueError:
return jsonify(['Invalid submission'])
# Number is now type integer
if number < 2:
return jsonify(["the number is less than two"])
else:
return jsonify(["the number is not less than two"])
You can make a decorator that is a global exception handler:
import traceback
from flask import current_app
def set_global_exception_handler(app):
#app.errorhandler(Exception)
def unhandled_exception(e):
response = dict()
error_message = traceback.format_exc()
app.logger.error("Caught Exception: {}".format(error_message)) #or whatever logger you use
response["errorMessage"] = error_message
return response, 500
And wherever you create your app instance, you need to do this:
from xxx.xxx.decorators import set_global_exception_handler
app = Flask(__name__)
set_global_exception_handler(app)
This will handle all exceptions generated in your application along with whatever else you need to do to handle them. Hope this helps.
your problem is caused because your program runs in debug mode.
for linux there is a tool called gunicorn. you should set up gunicorn and it will run again your flask app every time it crashes so you wont need to restart by yourself.
i dont know if there is a tool for windows.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm just started to learn back-end web development using Python and Flask framework.
My first application is the simplest one and it returns "Hello World!" when the user send a request for website's homepage.
Below, you can see the structure of my application :
myWebsiteDirectory/
app/
__init__.py
setup.py
wsgi.py
And below you see the content of the python files:
setup.py
from setuptools import setup
setup(name='YourAppName',
version='1.0',
description='OpenShift App',
author='Your Name',
author_email='example#example.com',
url='http://www.python.org/sigs/distutils-sig/',
install_requires=['Flask>=0.10.1'],
)
wsgi.py
#!/usr/bin/python
import os
#virtenv = os.environ['OPENSHIFT_PYTHON_DIR'] + '/virtenv/'
virtenv = os.path.join(os.environ.get('OPENSHIFT_PYTHON_DIR','.'), 'virtenv')
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
pass
#
# IMPORTANT: Put any additional includes below this line. If placed above this
# line, it's possible required libraries won't be in your searchable path
#
from app import app as application
#
# Below for testing only
#
if __name__ == '__main__':
from wsgiref.simple_server import make_server
httpd = make_server('localhost', 8051, application)
# Wait for a single request, serve it and quit.
httpd.serve_forever()
__init__.py
from flask import Flask
app = Flask(__name__)
app.debug = True
#app.route('/')
def not_again():
return 'Hello World!'
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
What is my question:
What happens when I upload this files on the server and what happens when a user request my website?
In the other words:
When Python interpret Each one of the above files on the server? (And how many times each file interpret)?
What happens when a user send a request? His/Her request make a file re-interpreted or the request refers to a running function as an argument? If so, shouldn't there is an infinite loop on the server to catch the request? if so, where is that infinite loop?
What happens when a user send a request when the web server is not finished the previous request yet? Those the argument/script refers/interpret again in a separate environment for this new user or he/she must wait for server to finish answering the previous request?
And again, in the other words:
How user's requests handle on a web server?
Although the above question is based on Python & Flask web framework web developing, but it there is a general mechanism for all the languages and frameworks, please let me know that general procedure and not this specific case.
If you have no good idea about how a web server works, since you are interested in Python, I suggest you have a read of:
http://ruslanspivak.com/lsbaws-part1/
http://ruslanspivak.com/lsbaws-part2/
http://ruslanspivak.com/lsbaws-part3/
If interested then in a walk through of doing something with a Python web framework to build a site, then also consider reading:
http://tutorial.djangogirls.org/en/index.html
It is a good basic introduction to get people going.
These will give you fundamentals to work with. How specific WSGI servers or service providers work can then be a bit different, but you will be better able to understand by working through the above first.
I've been trying for a few days now to get Google App Engine to run a cron Python script which will simply execute a script hosted on a server of mine.
It doesn't need to post any data to the page, simply open a connection, wait for it to finish then email me.
The code I've previously written has logged as "successful" but I never got an email, nor did I see any of the logging.info code I added to test things.
Ideas?
The original and wrong code that I originally wrote can be found at Google AppEngine Python Cron job urllib - just so you know I have attempted this before.
Mix of weird things was happening here.
Firstly, app.yaml I had to place my /cron handler before the root was set:
handlers:
- url: /cron
script: assets/backup/main.py
- url: /
static_files: assets/index.html
upload: assets/index.html
Otherwise I'd get crazy errors about not being able to find the file. That bit actually makes sense.
The next bit was the Python code. Not sure what was going on here, but in the end I managed to get it working by doing this:
#!/usr/bin/env python
# import logging
from google.appengine.ext import webapp
from google.appengine.api import mail
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
import logging
class CronMailer(webapp.RequestHandler):
def get(self):
logging.info("Backups: Started!")
urlStr = "http://example.com/file.php"
rpc = urlfetch.create_rpc()
urlfetch.make_fetch_call(rpc, urlStr)
mail.send_mail(sender="example#example.com",
to="email#example.co.uk",
subject="Backups complete!",
body="Daily backups have been completed!")
logging.info("Backups: Finished!")
application = webapp.WSGIApplication([('/cron', CronMailer)],debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
Whatever it was causing the problems, it's now fixed.