I want to ask for help. I want to use pymongo and flask, for an API on the virtual machine. I was able to install MongoDB, flask_pymongo and flask. I created a database in MongoDB and a collection named LicencePlate. And also wrote the following code.
from flask import Flask, jsonify, request
from flask_pymongo import PyMongo
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'LicencePlate'
app.config['MONGO_URI'] = 'mongodb://localhost:27017/db'
mongo = PyMongo(app)
#app.route('/framework', methods=['GET'])
def get_all_frameworks():
framework = mongo.db.LicencePlate
output = []
for q in framework.find():
output.append({'name' : q['nom'], 'language' : q['prenom']})
return jsonify({'result' : output})
if __name__ == '__main__':
app.run(debug=True)
But when running this code nothing happens when I make a get request, error
Error: Couldn't connect to server
Related
I'm not getting the proper response for this particular API. Also , In actual implementation, I'm getting the proper 200 jsonify response when all things are running fine but if their is any exception and If I want to send back the response with 500 status code : the postman say Could not get response : "Error: read ECONNRESET" and in my console it display as "127.0.0.1 - - [04/Aug/2020 23:57:22] "←[37mPOST /hi HTTP/1.1←[0m" 500 -"
can someone please tell me , where I'm going wrong ?
from flask import Flask, jsonify, request, abort, json
from werkzeug.utils import secure_filename
from werkzeug.exceptions import HTTPException
from flask_cors import CORS, cross_origin
import traceback
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
#app.route("/hi", methods=['POST'])
def hi():
val = 500
dict_json = {"messgae": "lets work it out {} ".format(val)}
return jsonify(dict_json), val
I had this problem today and found that it seems to be an issue with the flask server. It works fine usually however sometimes requests with postman would time out with the error you've mentioned.
Can you try hosting it instead with waitress?
To do that add this to the top of your file
from waitress import serve
then instead of running app.run() you run serve(app, host='localhost', port=7777)
oh, and for waitress to work you will of course need to run pip install waitress first!
I've started to make an app using Python 3 with the Flask framework. I mostly followed this tutorial. I'm currently using a free-tier AWS Ubuntu-16.04 server to host the app on while trying to develop it.
How am I meant to see the errors that my Flask App is returning? - as most of the time I receive a 500 Internal Server Error in my browser. Also is there an easier setup I should be using to develop and debug the app.
Thanks
Edit 1:
#!/usr/bin/python
from flask import Flask, render_template, request
app = Flask(__name__)
app.debug = True
#app.route('/table')
def current_return():
data = ['one', 'two', 'three']
return render_template("current.html",data = data)
if __name__ == "__main__":
app.run()
You should enable debugging for your app.
app = Flask(__name__)
app.debug = True
That will output the traceback on the error pages, instead of just a generic 'Server error' page.
I have created a flask application and am hosting it on a Ubuntu server. I know that my apache config is correct since I am able serve the example flask application. However, this one seems to be giving me trouble. The code is below:
from flask import Flask, render_template, request, url_for
import pickle
import engine
import config
# Initialize the Flask application
app = Flask(__name__)
model = pickle.load(open(config.MODEL_PATH, "rb"))
collection = engine.Collection(config.DATABASE_PATH)
search_engine = engine.SearchEngine(model, collection)
#app.route('/')
def form():
return render_template('index.html')
#app.route('/search/', methods=['POST'])
def search():
query = request.form['query']
results = search_engine.query(query)
return render_template('form_action.html', query=query, results=results)
#app.route('/retrieve/<int:item_number>', methods=['GET'])
def retrieve(item_number):
item = engine.Product(item_number, collection.open_document(str(item_number)))
return render_template('document.html', item=item)
if __name__ == '__main__':
app.run()
When running the file directly through the python interpreter, it works fine and I can access. However, when starting through apache and wsgi, I get no response from the server. It just hangs when making a request and nothing is available on the logs.
I suspect that my issue may have something to do with the three objects I initialize at the beginning of the program. Perhaps it gets stuck running those?
Update: I have tried commenting out certain parts of the code to see what is causing it to stall. Tracing it out to the engine module, importing NearestNeighbors seems to be causing the issue.
import sqlite3
import config
from sklearn.neighbors import NearestNeighbors
from preprocessor import preprocess_document
from collections import namedtuple
I am a first time user of pythonanywhere
I first started by doing a git clone of my code from github through the bash console. I did not use a virtual environment. My WSGI app was invoked in my app.py file. Also, my code uses sqlalchemy to interact with my database.
Basically, the flask app was like a custom api that returned JSON for GET and POST requests and I am having trouble viewing the JSON output. I am not sure what exactly I am doing wrong or missing.
Code in app.py file:
#!flask/bin/python
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_declarative import Base, Quote
from flask import request
from flask import abort
import json
#connect to database
engine = create_engine("sqlite:///quotes.db")
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
app = Flask(__name__)
#app.route("/trumptext/api/quotes", methods=["GET"])
def get_quotes():
quoteList = session.query(Quote).all()
result = []
for q in quoteList:
my_dict = {}
my_dict["id"] = q.id
my_dict["quote"] = q.quote
result.append(my_dict)
return json.dumps(result,ensure_ascii=False).encode('utf8')
#app.route("/trumptext/api/quotes", methods=["POST"])
def add_quote():
if not request.json or not "quote" in request.json:
abort(400)
new_quote = request.json["quote"]
q = Quote(quote=new_quote)
session.add(q)
session.commit()
quoteList = session.query(Quote).all()
last = quoteList[-1]
result = []
my_dict = {}
my_dict["id"] = last.id
my_dict["quote"] = last.quote
result.append(my_dict)
return json.dumps(result,ensure_ascii=False).encode('utf8'), 201
if __name__ == "__main__":
app.run()
Also, code in /var/www/nnelson_pythonanywhere_com_wsgi.py:
import os
import sys
path = '/home/nnelson/trumptextapi'
if path not in sys.path:
sys.path.append(path)
from app import app as application
If I enter something like :
http://nnelson.pythonanywhere.com/trumptext/api/quotes (to perform a GET request)
It should ideally return all the quotes stored in the quotes.db database in JSON format, however all I get it output that looks like this: [] I tested my code on localhost using the curl tool and it works just fine. I am having trouble hosting it though
Any help is appreciated.
You're using a relative path to your database, so it's probably looking at a database that you don't expect. Use a full path to the database or make it relative to the path of your app.py file so that you know where it's getting the database from.
My python app does not throw any errors on Google App Engine, but the Allow-Control-Access-Origin header is never sent. How can I ensure that I am sending it with flask-cors?
import MySQLdb
import os
import webapp2
import json
import flask
from flask import Flask, jsonify, render_template, request
from flask.ext.cors import CORS, cross_origin
app = Flask(__name__)
#app.route('/')
#cross_origin()
def do_search():
if (os.getenv('SERVER_SOFTWARE') and
os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')):
db = MySQLdb.connect(unix_socket='/cloudsql/my-instance-name:storeaddressdb', db='store_locator', user='myuser', passwd='password')
else:
db = MySQLdb.connect(host='localhost', user='root')
cursor = db.cursor()
query = 'SELECT * FROM stores WHERE 1 LIMIT 5'
cursor.execute(query)
resp = jsonify(data=cursor.fetchall())
return resp
db.close()
It appears that this code actually does work, although I do not see the Allow-Control-Access-Origin header when I use cURL to test the url. The logs in Google App Engine show CORS selectively adding the header unless the client specifically skipped it. Also, the Javascript client is no longer showing an error, and receives the data. It may not be the prettiest python code, but it is functionally correct for my purposes.