The first I did, was getting in my puTTY and installing flask and apache2 following this guide over here. Everything went smoothly, commands did what they had to do and it raised 0 problems. Until here, fine.
Then, in order to complete my application, I needed 2 things: phantomJS() and selenium. When I want to install selenium, I write the command
sudo apt-get install selenium
then I run
selenium
to make sure it's indeed running. Then when I import selenium in my code, it no longer gives me a server error, which is great.
I installed then phantomjs with the command
sudo apt-get install phantomjs
Previously, I had an error when I typed
phantomjs
But now I no longer do, phantomjs it getting recognized and not giving errors.
However, when I try to load my form with the post method, it doesn't do anything as it did in localhost.
In localhost, when I sent some info over POST method, a new window browser would load in the background thanks to phantomjs, would extract some keywords and display them in a new table.
However, when I do the same from the server, it doesn't show no errors but also it doesn't do nothing. It loads a bit (a milisecond) and stops, without giving errors or doing what's supposed to do.
The code:
from flask import Flask, render_template, request, url_for, redirect, flash, session
import selenium
from selenium import webdriver
nombres = []
app = Flask(__name__)
app.secret_key = "a super secret key"
#app.route('/', methods = ['GET', 'POST'])
def homepage():
error=None
try:
if request.method == 'POST':
name = request.form['name']
city = request.form['city']
#browser = webdriver.Firefox()
browser = webdriver.phantomjs()
browser.set_window_size(1120, 550)
browser.implicitly_wait(10)
browser.get('thewebpagehere') #this is on purpose, changed
browser.quit()
return redirect(url_for('dashboard'))
elif request.method == 'GET':
return render_template("main.html")
except Exception as e:
flash(e)
#app.route('/dashboard/')
def dashboard():
return render_template("dashboard.html", nombres=nombres)
if __name__ == "__main__":
app.run()
I removed a lot of code that came after the browser loaded, for space purposes, but basically it's just code that scraped the site. With that code or without it, it's still not even opening a hidden browser with phantomjs and I'm not sure why.
Should I do something different? Please feel free to tell me if my post needs something else (I know error handling looks horrific, I'm not worried about that right now), or you need additional information, i've been with this for a week and I can't find answers from anyone.
Thanks for your time.
EDIT: i'm a bit dumb
Related
I am new to flask. I am making a simple web-based app. However, one of the url is not working. All the other pages are working fine
My python code
from flask import Flask, render_template, request
from openpyxl import load_workbook
app = Flask(__name__)
# Report Main Page
#app.route('/report')
def report():
return render_template('report.html')
if __name__ == '__main__':
app.run(debug=True)
It have some other pages. All are working fine. However /report is not working, It returns a 404 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 just created one web app with the help of Flask and Heroku but when I started using session for log in stuff then in local (in my computer) its working fine but when I deployed it on heroku then its showing error: Internal Server Error
Can anyone help me with this ?
#app.route('/')
def home():
''' Home page'''
if 'username' in session:
session['logged_in'] = True
else:
session['logged_in'] = False
return render_template('home.html')
As soon as it come to 'if' line then server stops and shows error but if i run this locally then it works fine. I just pasted the small part of my code showing where it shows error.
Is it possible that for heroku we need to implement it differently or heroku doesn't support session.
Check if you have set app.config['SECRET_KEY']. If not, flask will report an error.
I have a simple flask application deployed using CGI+Apache running on a shared hosting server.
The app runs Flask 0.11.1 on Python 2.6 along with Flask-Mail 0.9.1.
One of the pages in the app has a contact form that sends an email and redirects back to the same page.
The contact form has a POST action to '/sendmail' that is defined in Flask controller as follows -
#app.route("/sendmail", methods=['GET','POST'])
def send_mail():
print "Sending Email"
mail = SendMail(app)
mail.send_mail(request.form['name'], request.form['mail'], request.form['phoneNo'], request.form['message'])
return render_template('contact.html')
Here's the issue -
With the code above, the app sends me an email successfully, however then gives an error '/sendmail' not found. The template fails to render.
If I remove the print statement from the snippet, the app renders contact.html successfully after sending the email.
What explains the behaviour of print statement in the snippet? Considering the execution is sequential, shouldn't the block fail at the print statement itself without sending the email instead of failing during rendering the template?
Print statement should not create an error as it is one of the statement like others. Instead since you are not checking for request.method=='POST', this should create and throw an error in your get request. To redirect to the same page return redirect("/sendmail") Do not forget to import from flask like this from flask import redirect
I'm writing an app using Flask.
I have a set of routes and they work.
What I want to do on the client side is to ignore any requests to invalid URLs. That is I do not want to render any 404/error pages in the app. I would like an alert that says the URL is invalid and for the browser to simply stay on the same page.
I don't want to be checking the URLs in JavaScript on the client, as this would expose them.
I have a route which responds correctly to unknown URLs:
#app.errorhandler(404)
def non_existant_route(error):
return jsonify({"no":"such page"})
If I delete the return statement I get a 500 error.
I can't use abort()
Does this idea violate some HTTP principle?
Thanks
It sounds like you need a "catch-all" endpoint. Typically, it seems a catch-all endpoint would return a generic 404, but in your case, you probably want to return a 200 with some contextual information. Here's basically how you can do it (credit goes to http://flask.pocoo.org/snippets/57/):
from flask import Flask
app = Flask(__name__)
#app.route('/', defaults={'path': ''})
#app.route('/<path:path>')
def catch_all(path):
# returns a 200 (not a 404) with the following contents:
return 'your custom error content\n'
# This is just one of your other valid routes:
#app.route('/stuff')
def stuff():
return 'stuff\n'
if __name__ == '__main__':
app.run()
If you run this and curl various endpoints of the test app, here's what you get:
$ curl localhost:5000/stuff
stuff
$ curl localhost:5000/foo/bar
your custom error content
$ curl localhost:5000/otherstuff
your custom error content
As you can see, your other routes will still work as you expect.
I've decided a solution to this is too hard! I can not find any way to get the browser to ignore a response. There is no response header for 'do nothing'. If there was we would probably never see a webserver error again, which would not be good.
I could ajaxify all the requests as a way to grab the response headers and analyze them before any rendering or redirecting happens. That starts to break all the navigation (back buttons at least) and the pretty URLs. I could bung in a JS routing framework etc, and while I'm leaning how it works I'm not building my app (I already have enough to learn!)
#app.errorhandler(404)
def page_not_found(error):
return redirect(url_for('index'))
If you come up with something great post it anyway, I'm not the first to ask this question, and probably not the last.
Thanks
I remember reading about a javascript library some days ago (but I don't remember the name...). The clou with this library was, that all links and form submits were loaded not directly into the browser "_top" frame/window but into a hidden div and afterwards, when done, the content of the page was replaced by the content of this hidden div.
So if you want to catch bad links and such on client side you could hook up all links and submits and check the http response code. If it is not 200 (ok) you display an error. If it is okay you decide, if you replace the old page with the new content.
But there are two problems with this solution:
1. You would have to change the browsers location (in the address bar) without reloading the page of course!
2. It might get tricky to post some file uploads with javascript.
If I find the link or name of the js-library I saw, I will tell you!
Is there a way to call a python function when a certain link is clicked within a html page?
Thanks
You'll need to use a web framework to route the requests to Python, as you can't do that with just HTML. Flask is one simple framework:
server.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('template.html')
#app.route('/my-link/')
def my_link():
print 'I got clicked!'
return 'Click.'
if __name__ == '__main__':
app.run(debug=True)
templates/template.html:
<!doctype html>
<title>Test</title>
<meta charset=utf-8>
Click me
Run it with python server.py and then navigate to http://localhost:5000/. The development server isn't secure, so for deploying your application, look at http://flask.pocoo.org/docs/0.10/quickstart/#deploying-to-a-web-server
Yes, but not directly; you can set the onclick handler to invoke a JavaScript function that will construct an XMLHttpRequest object and send a request to a page on your server. That page on your server can, in turn, be implemented using Python and do whatever it would need to do.
Yes. If the link points to your web server, then you can set up your web server to run any kind of code when that link is clicked, and return the result of that code to the user's browser. There are many ways to write a web server like this. For example, see Django. You might also want to use AJAX.
If you want to run code in the user's browser, use Javascript.
There are several ways to do this, but the one that has worked best for me is to use CherryPy. CherryPy is a minimalist python web framework that allows you to run a small server on any computer. There is a very similiar question to yours on stackoverflow - Using the browser for desktop UI.
The code below will do what you want. Its example 2 from the CherryPy tutorial.
import cherrypy
class HelloWorld:
def index(self):
# Let's link to another method here.
return 'We have an important message for you!'
index.exposed = True
def showMessage(self):
# Here's the important message!
return "Hello world!"
showMessage.exposed = True
import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(HelloWorld(), config=tutconf)
else:
# This branch is for the test suite; you can ignore it.
cherrypy.tree.mount(HelloWorld(), config=tutconf)
I personally use CherryPy in combination with several other modules and tools:
Mako (template library)
py2exe (convert into Windows executable)
GccWinBinaries (used in combination with py2exe)
I wrote an article about Browser as Desktop UI with CherryPy that introduces modules and tools used plus some further links that might help.
In addition to running Python scripts on a server, you can run Python scripts on the client-side using Skulpt.