While trying to run the following code:
from flask import FLASK, render_template, request, jasonify
I am getting the following error:
ImportError: cannot import name 'FLASK' from 'flask' (C:\Users\karti\Anaconda3\envs\venv\lib\site-packages\flask\__init__.py)
Python is case sensitive. Also check your spelling on jasonify:
from flask import Flask, render_template, request, jsonify
The Flask object is written in title case, not all caps. I also suspect you meant jsonify (JSON is short for JavaScript Object Notation) instead of jasonify which is how it's pronounced. You can find the API reference here: https://flask.palletsprojects.com/en/1.1.x/api/#template-rendering
Related
So I've created a database called "school" which appears in the ArangoDB web UI. However after running my app.py file I receive the following trace error in the command prompt which prevents the python server from booting up.
Note: I'm running Python 3.7.3 and Flask 1.0.2 with the python driver pyArango-1.3.2 to connect to ArangoDB version 3.4.6-1
Here's the rather simple code I'm using...
from flask import Flask, session, render_template, redirect, flash, url_for, send_from_directory, request
from flask_cors import CORS
from werkzeug.utils import secure_filename
from pyArango.connection import *
conn = Connection(username="root", password="password")
conn.createDatabase(name="school")
db = conn["school"]
Any idea what might be causing the error below?:
File "C:\Users\username\newproject_v2\newprojectv2\app.py", line 9, in <module>
conn.createDatabase(name="school")
File "C:\Users\username\Envs\newprojectv2\lib\site-packages\pyArango\connection.py", line 163, in createDatabase
raise CreationError(data["errorMessage"], r.content)
pyArango.theExceptions.CreationError: duplicate name. Errors: b'{"error":true,"errorMessage":"duplicate name","code":409,"errorNum":1207}'
I think you can create a database only once. Check if the connection already has a db with the same name. If it doesn't exists then create one. hasDatabase can help you there.
from flask import Flask, session, render_template, redirect, flash, url_for, send_from_directory, request
from flask_cors import CORS
from werkzeug.utils import secure_filename
from pyArango.connection import *
conn = Connection(username="root", password="password")
if not conn.hasDatabase("school"):
conn.createDatabase(name="school")
db = conn["school"]
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))
This question already has an answer here:
Flask view raises TypeError: 'bool' object is not callable
(1 answer)
Closed 6 years ago.
I am trying to transition my workflow into Flask to write a simple web interface for a Python script.
However, doing the following, raises a type error constantly:
from flask import Flask, render_template, request
import sqlite3
app = Flask(__name__)
#app.route('/restart/<int:id>')
def restart(id):
return id
if __name__ == '__main__':
app.run()
I would basically just like to show the id that is passed in the URL.
Am I missing something? This is exactly how I would do this in Django for example and all the examples on the Net have pointed to this approach in Flask.
Your route function should be returning a string but you're returning the integer you're passing into it. Cast it to a string instead:
from flask import Flask, render_template, request
import sqlite3
app = Flask(__name__)
#app.route('/restart/<int:id>')
def restart(id):
return str(id)
if __name__ == '__main__':
app.run()
I am trying to follow this tutorial...
http://flask.pocoo.org/docs/tutorial/setup/#tutorial-setup
Trying to get a simple flask app to run. I think I have followed their code almost exactly, yet I am having problems. My code is....
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
# configuration
DATABASE = ''
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
sandra_source= Flask(__name__)
sandra_source.config.from_object(__name__)
def main():
sandra_source.run()
main()
I recognize the DB is not the same, but other than that, it is pretty spot on. However, I keep getting the error
AttributeError: 'module' object has no attribute 'sandra_service'
My module is named sandra_service, so I'm not sure how this error is happening.
Stack trace
AttributeError: 'module' object has no attribute 'sandra_service'
0 SandraImporter.load_module() c:\working\qzpkgs\quartz-14324978\win32_vc9\pylib\sandra\sandra_import.py:208
1 <module>() /playground/nbkiq0w/rester_app_root/services/sandra_service.py:20
2 Config.from_object() D:\quartz\WINSLA~1\WIN32-~1\build\ext\noarch\lib\python2.6\flask\config.py:146
3 --> import_string() D:\quartz\WINSLA~1\WIN32-~1\build\ext\noarch\lib\python2.6\werkzeug\utils.py:529
Not sure if this is a great answer or not, but I removed
sandra_source.config.from_object(__name__)
this line, and now the code seems to be at least compiling/running. Hopefully more issues won't present themselves later on.
I'm having trouble with the MongoHQ Heroku addon. Locally my app works and the os variable is present and well-formed on Heroku. However, when I attempt to access the db it throws an error: OperationFailure: database error: unauthorized db:my_database ns:my_database.cars lock type:0 client:128.62.187.133. If I try to hard-code the connection string from MongoHQ and run locally, I get the same error.
My app is below:
import os
import datetime
from flask import Flask
from flask import g
from flask import jsonify
from flask import json
from flask import request
from flask import url_for
from flask import redirect
from flask import render_template
from flask import make_response
import pymongo
from pymongo import Connection
from bson import BSON
from bson import json_util
app = Flask(__name__)
def mongo_conn():
# Format: MONGOHQ_URL: mongodb://<user>:<pass>#<base_url>:<port>/<url_path>
if os.environ.get('MONGOHQ_URL'):
return Connection(os.environ['MONGOHQ_URL'])
else:
return Connection()
#app.route('/', methods=['GET', 'POST'])
def hello():
# Get your DB
connection = mongo_conn()
db = connection.my_database
# Create an object
car = {"brand": "Ford",
"model": "Mustang",
"date": datetime.datetime.utcnow()}
# Get your collection
cars = db.cars # crashes
# Insert it
cars.insert(car)
...
Edit: MongoHQ support helped me. Problem was that I was calling my database my_database instead of the actual DB name given to me by the MongoHQ addon. E.g., db = connection.app52314314. That change fixed it.
You likely need to run the authenticate command against the DB directly after you connect.
Try something like this:
db.authenticate([USER], [PASSWORD])
If that doesn't work, feel free to email support#mongohq.com and we can help you out with your specific DB.
You don't need to do all that. You can simply:
from pymongo import MongoClient
client = MongoClient(os.environ['MONGOHQ_URL'])
mongo_db = client.get_default_database()
It will automatically authenticate you, and connect to the provisioned database, the <url_path> part of your connection url.