Passing id in route producing uncallables [duplicate] - python

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()

Related

unable to access flask with postman [duplicate]

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()

How to pass data from flask to html file continuously? [duplicate]

This question already has answers here:
Display the contents of a log file as it is updated
(3 answers)
Closed 3 years ago.
I have script which executes for 10 minutes and generates logs/outputs while executing..i want these logs to be passed to html file using flask.
You can use ajax methods in your javascript code to ask server for new logs/outputs with any period.
You can open WebSocket and write your logs to client in real-time. Look at example on flask-socketIO documentation: https://flask-socketio.readthedocs.io/en/latest/ or somewhere else.
Here is example how to send message to client:
from flask import Flask, render_template
from flask_socketio import SocketIO, send
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
#socketio.on('message')
def handle_message(message):
send(message)
if __name__ == '__main__':
socketio.run(app)

Add Flask routes to a class's methods [duplicate]

This question already has answers here:
Extending Flask class as main App
(1 answer)
Python3 Flask - missing 1 required positional argument: 'self'
(1 answer)
Closed 5 years ago.
I'm trying to write a server to manage some data and serve webpages. I'd like to use Flask, the Python web framework.
I can easily set up a "static" Flask app that serves a page for fixed data, doing something like
from flask import Flask, render_template
DATA = [1, 2, 3]
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
#app.route('/')
def index():
return render_template('mytemplate.html', data=DATA)
if __name__ == '__main__':
app.run()
but what I'd like is a "dynamic" app, with a Server which manages changing data. I'd like the Server to serve the most current data when a page is opened. So I'd like to do something like the following:
from flask import Flask, render_template
app = Flask(__name__)
class Server():
def __init__(self, data):
self.data = data
###
### Other long-running methods which might update self.data
###
#app.route('/') # <--- causes an error
def index(self):
return render_template('mytemplate.html', data=self.data)
if __name__ == '__main__':
s = Server([1, 2, 3])
### Spawn long-running methods
app.run()
However, doing this raises an error:
TypeError: index() takes exactly 1 argument (0 given)
I've seen that I can achieve what I want by wrapping my methods in Flask routes outside the class definition, after instantiating my server, by doing this:
if __name__ == '__main__':
s = Server([1, 2, 3])
### Spawn long-running methods that might update s.data
app.route('/')(s.index)
app.run()
but this seems exceptionally messy! It would be so much clearer and more logical if the routes were attached to the actual methods I'd like to use to serve the pages.
So my question is: is there a way to add Flask routes directly to methods inside a class?
Many thanks in advance

Python Flask: render_template - 'dict' object is not callable [duplicate]

This question already has answers here:
Flask view raises TypeError: 'bool' object is not callable
(1 answer)
Return JSON response from Flask view
(15 answers)
Closed 5 years ago.
I'm trying to using Flask Blueprint to make routes from another file. This is my "catalog.py file:
from flask import Blueprint, make_response, render_template
from models.catalog import Catalog
catalog_url = Blueprint('catalog_url', __name__)
#catalog_url.route("/")
#catalog_url.route("/catalog")
def show_all_catalogs():
try:
catalogs = Catalog.find_all_catalogs()
return render_template('publiccatalogs.html', catalogs=catalogs)
except:
return {'message': 'Internal Server Error'}, 500
This is my "app.py" file:
from catalog import catalog_url
app = Flask(__name__)
app.register_blueprint(catalog_url)
But when I enter "localhost:5000/catalog", it returns this error:
TypeError: 'dict' object is not callable
I tried returning plain text and even JSON, they worked just fine. But when I try to use "render_template", I keep getting the same error.
There is try except, your code return render_template('publiccatalogs.html', catalogs=catalogs) is correct. However, I suspect the html template cannot be found, and then this exception happen, it goes to except return {'message': 'Internal Server Error'}, 500 this part format is not correct.
In Flask, a view must return one of the following:
a string
a Response object (or subclass)
a tuple of (string, status,headers) or (string, status)
a valid WSGI application

flask context inside context , for jsonfy, all in a single page

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))

Categories