I am trying to render an HTML page on local host with restful flask api. The content of HTML page gets displayed as string with "" rather than the page.
class data(Resource):
def get(self):
#return "Welcome!"
return render_template('index.html')
api.add_resource(data,'/')
My index.html file contains the following content
<!DOCTYPE html>
<html>
<body>
<h1>Welcome to the site!</h1>
</body>
</html>
After running the code, on the webpage(http://localhost:5000/) I get the following content
"<!DOCTYPE html>\n<html>\n<body>\n<h1>Welcome to the Data Hosting Service</h1>\n</body>\n</html>"
On the other hand,It is returning the text "Welcome!" normally. Can you help me ?
Update:
With the help from users, I have fixed this problem by changing the response type as follows,
from flask import Response, render_template
return Response(render_template('index.html'),mimetype='text/html')
You may need import make_repsone from flask to render your html with headers information.
from flask import make_response, render_template
headers = {'Content-Type': 'text/html'}
return make_response(render_template('index.html'),200,headers)
Hope this could be helpful.
Related
I'm trying to get a simple web form up and running that only asks for a URL.
This is the HTML Code (index.html)
<!DOCTYPE html>
<html>
<body>
<form name = 'test' action = "." method = "post">
<form action="test.php" method="get">
URL <input type="text" link="link" name = "URL"/>
<input type="submit" />
</form>
</body>
</html>
I'm using Flask to run the simple web application this is the Flask Code: (app.py)
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/")
def index():
return render_template('index.html')
#app.route("/", methods = ["POST"])
def get_value():
url = request.form["URL"]
return 'The url is ' + url
if __name__ == "__main__":
app.run(debug=True)
and I'm trying to get the inputted URL to another python script so I can do something with it, this is the other python script: (url.py)
from app import get_value
print(get_value())
However, whenever I run python3 url.py it gives me this error:
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.
Any idea how to print get the URL over successfully? In a lot of detail preferably because I am very new to Flask.
The error occurs because you called a function that needs data from a request to get the user inputs. You should call the url handling function instead letting the handling function call the retrieval of the url.
Consider this answer https://stackoverflow.com/a/11566296/5368402 to make sure you pass the url correctly. Now that you have your url, simply pass it to your other script.
import url # your url.py module
#app.route("/", methods = ["POST"])
def get_value():
input_url = request.form["URL"]
url.handle_url(input_url) #call a function inside url.py
I am trying to create a web page using python and flask on pythonanywhere.com
The page is very simple. The user will enter a url in the box and click submit, the page then shows the url they submitted.
I am trying to do it on one page. If the method is GET, then display the form and allow the user to submit a url. If the method is POST, then print the url passed in the form.
I tried it multiple ways but it did not work. I can see the form and submit the url, but could never print it or put every thing in one page
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route("/", methods = ['GET', 'POST'])
def index():
return '''
<form action="process" method="post">
<p>Enter a URL for a\ web page:</p>
<input type="text" name="url"></input>
<input type="submit" value="Process"></input>
</form>'''
#app.route("/process", methods = ['GET', 'POST'])
def process():
url = request.form['url']
print("The url address is '" + url + "'")
When you print, this would go into your PythonAnywhere webapp logs. Instead, if you want to get that back as a website response, you would have to return it.
(and also reload your webapp after you make any changes)
I have started learning flask for web development and experimenting with it since I have a website in mind I would like to create.
My thought has been to create a homepage showing some data that will be updated using cURL or the requests python library. I have some other python code that generates the data to be displayed and I would like to use the POST request for sending a dictionary with the generated information to the server and update the homepage with that new info.
A rather simplistic but comprehensive version of what I have tried so far:
from flask import Flask, redirect, url_for, render_template, request
app = Flask(__name__)
#app.route("/", methods=["POST", "GET"])
def home():
if request.method == "POST":
data = request.form["data"]
return render_template("index.html", content=data)
else:
return render_template("index.html", content="initial_data")
if __name__ == "__main__":
app.run(debug=True)
The code for index.html
<!doctype html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
{{content}}
</body>
</html>
So I would like to send a POST request with some new data to the server and update the webpage with that new data.
import requests
payload = {'data': 'new_data'}
r = requests.post("http://localhost:5000/", data=payload)
All of the above doesn't succeed in updating the data in the webpage when I send a request, it just stays the same. Am I totally off course? Is this even possible in the way I have thought of?
Any comment is much appreciated, thank you.
data is staying the same because it's being reassigned each time as a local variable. When a POST request happens, the variable is created, passed to the template, then destroyed as it goes out of scope.
Try this as an experiment in showing how a variable might persist between page loads, though only until the server restarts:
from flask import Flask, redirect, url_for, render_template, request
app = Flask(__name__)
app_state = {
'data': 'Initial Data'
}
#app.route("/", methods=["POST", "GET"])
def home():
if request.method == "POST":
app_state['data'] = request.form['data']
return render_template("index.html", content=app_state['data'])
if __name__ == "__main__":
app.run(debug=True)
In that example, you're creating a global dictionary, app_date, and updating a key on it every time the user sends a POST request to / with a form payload of data.
Then, we return the template with the content of the dictionary item.
A Few Notes
The implementation I provided would still be vulnerable to race conditions if two people make simultaneous changes.
For this kind of thing, you'll usually want a more persistent solution, like a database.
i had used an sample web form "index.html"(it is in templates folder) in which it contains a text box to enter email .then the data should be posted to sample.py and it should be printed.but it is not happening,it simply showing 404 not found after clicking signup in web form.here is my code,please correct me if i am wrong ,and also please tell me how to run this in pycharm 4.5.i am a beginner. please help me.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/signup" method="post">
<input type="text" name="email">
<input type="submit" value="Signup">
</form>
</body>
</html>
my python code
from flask import Flask,request,redirect
app = Flask(__name__)
#app.route('/signup', methods = ['POST'])
def signup():
email = request.form['email']
print("The email address is '" + email + "'")
return redirect('/')
In the code that you have posted there is no route or handler registered for /, however, signup() redirects to /. Thus you will always see a 404 error if you post to http://localhost:5000/signup (assuming that is the address of your Flask server).
Posting to `/signup' should result in the print message being displayed on your console. If that is happening then at least you know that the Flask server is working.
You should implement a handler for the / route; perhaps rendering index.html:
from flask import Flask,request,redirect
from flask import render_template
app = Flask(__name__)
#app.route("/")
def index():
return render_template('index.html')
#app.route('/signup', methods = ['POST'])
def signup():
email = request.form['email']
print("The email address is '" + email + "'")
return redirect('/')
app.run()
Now the redirect from the signup page should not result in 404 errors.
Run code (python app.py), then you can load http://localhost:5000 directly in your browser, and you should see the signup page displayed. Enter an email address and click "Signup". The text that you entered should be printed to the console in which you started the Flask server, and your browser should redirect back to the index page.
try action = "{{url_for('signup'}}"
also when you use print in flask it's seen on the console not the webpage
I'm following this tutorial to learn how to get OAuth2.0 login onto my site, and I'm having some problems. My site is registered on GAE and I have my client ID. I also pip installed google-api-python-client. However, I don't know what to import into my project. I have two pages in my application. One that handles authorization and one that actually has the page.
authorize.py
import cgi, webapp2
from google.appengine.api import users
LOGIN_PAGE_HTML="""\
<html>
<body>
<input type="submit" method="post" action="/AuthorizeUser"/>
</body>
</html>
"""
class LoginPage(webapp2.RequestHandler):
def get(self):
self.response.write(LOGIN_PAGE_HTML)
class AuthorizeUser(webapp2.RequestHandler):
def post(self):
state = ''.join(random.choice(string.ascii_uppercase + string.digits)for x in xrange(32))
session['state'] = state
response = make_response('/LandingPage',
CLIENT_ID='MY ID',
STATE=state
APPLICATION_NAME='Summit Tech Help'))
if request.args.get('state','') != session['state']:
response = make_response(json.dumps('Invalid state parameter.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
application = webapp2.WSGIApplication([
('/',LoginPage),
('/AuthorizeUser',AuthorizeUser),
], debug=True)
landing.py
import cgi, webapp2
from google.appengine.api import mail
LANDING_PAGE_HTML="""\
<html>
<body>
<p>test</p>
</body>
</html>
"""
class LandingPage(webapp2.RequestHandler):
def get(self):
self.response.write(LANDING_PAGE_HTML)
application = webapp2.WSGIApplication([
('LandingPage',LandingPage),
],debug=True)
My app.yaml has '-url: /.*' set to script:authorize.application
Any help would be much appreciated!
~Carpetfizz
to use a 3rd party module you need to import it in your app, if that's what you meant to ask,
also do check this link to use external libraries in gae.
You can check this example app for using Oauth2.0 in GAE