I'm trying to get data from another of my servers. The other server is just an html file with "Hello World" I can reach my homepage fine, but when I go to /farmdata, I get this error:
NameError: name 'Response' is not defined"
from flask import Flask, render_template
import requests
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/farmdata')
def farmdata():
r = requests.get('http://74.114.75.91:8080')
r.url
r.encoding
return Response(
r.text,
status=r.status_code,
content_type=r.headers['content-type'],
)
if __name__== '__main__':
app.run(debug=True, port=80, host='0.0.0.0')
Edit - to anyone else with the problem, this was the solution.
from flask import Flask, render_template, Response
You have never defined Response. If you want to use flask.Response, you either have to import flask and then access it via flask.Response, or from flask import Response and then simply use Response.
In your code, you import Flask from the flask module, and that's where you get Flask from. If you remove the from flask import Flask line, you'll get a NameError complaining about Flask not being defined as well.
In Python, a name is defined if:
you defined it via variable assignment [or with a def or a class statement, which is pretty much the same] (like app in your example)
you imported it from another module explicitly (like Flask)
it's defined on startup (like list)
Is there not a " ," too much before closing the brackets of the response?
Related
I want my web to be able to handle URLs inside the rule,
just like:
http://127.0.0.1:5000/tiyee?url=https://tiyee.cn/iyu2
but getting an error:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
I've tried with this code below but seems like it doesn't work
from flask import Flask, redirect
from tiyee import bypasser
app = Flask(__name__)
#app.route('/tiyee?url=<url>')
def _tiyee_redirect(url):
bypassed_json = bypasser(url)
return redirect(bypassed_json['bypassed_link'])
if __name__ == '__main__':
app.run(debug=True, port=5000)
Q: Is there a way to add URL inside the route rule?
example:
example.com/tiyee?url=https://tiyee.cn/iyu2 and get the https://tiyee.cn/iyu2
You are passing the url data in query. You will need to use request object to get the query value.
from flask import request
...
#app.route('/tiyee')
def _tiyee_redirect():
_url = request.args.get('url')
if _url is not None:
bypassed_json = bypasser(_url)
return redirect(bypassed_json['bypassed_link'])
my rest service sits at http://127.0.0.1:5000, but when i launch it, it gives me 404:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
why is that? I want my server to show some status msg like 'service ready'.
The actual function that i will use is accessible and works, when i press 'http://127.0.0.1:5000/parser/tengrinews' and hit enter it outputs the msg i coded in the function in my flask app:
[
"parsing this website :",
"tengrinews"
]
the main code:
from flask import Flask
import requests
from datetime import datetime
from flask import jsonify
app = Flask(__name__)
#this is my std method i can't see
#app.route("/http://127.0.0.1:5000/", methods = ['GET'])
def main():
return jsonify('service is ready')
#app.route("/parser/<string:website>", methods = ['GET'])
def parse(website):
return jsonify("parsing this website :", website )
if __name__ == "__main__":
app.run(debug=True)
Change this line -
#app.route("/http://127.0.0.1:5000/", methods = ['GET'])
to
#app.route("/", methods = ['GET']).
Because you have to specify only the extended URL that will be used. The #app.route decorator handles the rest for us
Note* (Don't do this. For fun only) -
If you wish to continue to use #app.route("/http://127.0.0.1:5000/", methods = ['GET']) then access the endpoint with the url - http://localhost:5000/http://127.0.0.1:5000/. You will get the response as "service is ready"
the api should include one function called "write text to file" and inputs a string parameter
as for the function to write to the disk I have no problem and I implemented the code my problem is how to set the rest API using python.
EDIT:
this is my code:
from flask import (
Flask,
render_template
)
import SocketServer
import SimpleHTTPServer
import re
app = Flask(__name__, template_folder="templates")
#app.route('/index', methods=['GET'])
def index():
return 'Welcome'
#app.route('/write_text_to_file', methods=['POST'])
def write_text_to_file():
f = open("str.txt", "w+")
f.write("hello world")
f.close()
if __name__ == '__main__':
app.run(debug=True)
anyhow when I try to test my rest api:
http://127.0.0.1:5000/write_text_to_file
I am getting the following error:
Now I'm trying to test my rest-api , however how can I make my code to start the server and to the test the post request api, this is my test_class:
import requests
import unittest
API_ENDPOINT="http://127.0.0.1:5000/write_text_to_file"
class test_my_rest_api(unittest.TestCase):
def test_post_request(self):
"""start the server"""
r = requests.post(API_ENDPOINT)
res = r.text
print(res)
also when runnning my request using postman I am getting internal_server_error:
You're doing a GET request for this url, but you've specified that this endpoint can only accept POST:
#app.route('/write_text_to_file', methods=['POST'])
Also, the SocketServer and SimpleHTTPServer imports are not needed with Flask.
The method is not allowed because Chrome (or any browser) makes GET requests.
Whereas, you defined it as POST
#app.route('/write_text_to_file', methods=['POST'])
Either change it to a GET method, or use a tool such as POSTMan to perform other HTTP call types
Sorry for ambiguous question, I'm not sure how better I can put it. So let me do the explanation of my problem.
I've the Flask application libindic, which has 2 Flask application one is frontend and other is api. So I've wsgi.py as follows
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
from silpa import api, frontend
import os
conffile = os.path.join(os.path.dirname(__file__), "etc", "silpa.conf")
application = DispatcherMiddleware(frontend.create_app(conffile),
{'/api': api.create_app(conffile)})
if __name__ == "__main__":
run_simple('0.0.0.0', 5000, application,
use_reloader=True, use_debugger=True)
The front end access works properly but when I hit /api/JSONRPC I get 404 error returned. This rule is defined as follows in silpa/api/jsonrpc.py
bp = Blueprint('api_jsonrpc', __name__, url_prefix='/api')
#route(bp, '/JSONRPC', methods=['POST'])
def handle_jsonrpc_call():
...
And when I print value of application and application.app and application.mounts in python interpreter I see folllowing
>>> application.app
<Flask 'silpa.frontend'>
>>> application.mounts
{'/api': <Flask 'silpa.api'>}
I'm unable to figure out why /api/JSONRPC results in 404. I'm not sure how can I debug it. I did check the app.url_map for api application and I can see rule for /api/JSONRPC registered there.
If some one can tell me what I might be doing wrong it would be a great help.
OK after debugging and stepping through Flask code I figured out the reason for the problem. The following line actually caused the problem
bp = Blueprint('api_jsonrpc', __name__, url_prefix='/api')
url_prefix should not be present in code because I'm already mounting this app at /api. Adding a /api url_prefix will result in following url instead /api/api/JSONRPC. Removing the above line fixed the issue.
So if you are mouting your app at different mount point than / using DispatcherMiddleware you should not url_prefix in blueprint.
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