Flask Page not found - python

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.

Related

Serving media file to podcast.app (iOS/MacOS) for download

I'm trying to create a simple podcast hosting web server with flask.
Streaming media files from the server works beautifully. However whenever I try and download the media for offline viewing my podcast app throws "Download error".
I've tried all sorts of headers and responses.
End point I'm using with relevant code (I hardcoded the filename for testing):
import os
import logging
from streamlink.exceptions import (PluginError)
from flask import Flask, redirect, abort, request
from flask import send_from_directory
def run_server(host, port, file_dir):
#app.route('/media', methods=['GET'])
def media():
return send_from_directory(file_dir, '6TfLVL5GeE4.mp4')
app.run(host=host, port=port, debug=True)
Podcast.app error log states:
Download failed due to error: Invalid asset: The original extension and resolved extension were not playable for episode url Optional(http://10.0.0.115:8084/media?id=6TfLVL5GeE4&provider=tw).
I can't for the life of me figure why it would fail for downloading but stream perfectly fine.
Please help!
Found out that you can not use parameters for a podcast feed url.
The url must include a filename.
For example: http://localhost/file.mp3

Publish a script online

I have a Python script written up and the output of this script is a list.
Right now I need to get it online and make it accessible to others. I looked at Django , but then I realized that it may be kind of hard to create the UI. Is there any simple way to create a UI in Django and map it to an existing Python script.
Right now I using nltk, numpy, sqlite3 and things like that. Or is there a simpler way by which I can proceed?
In your case, Django is redundant.
You can use something smaller, Flask or maybe Aiohttp.
For example, all you need in aiohttp:
basic hmtl template
handler for one url (here you will call your script)
aiohttp webserver
The main idea:
Your server catch some url (for example /),
start your script, receives result,
respond with your html template (also render script result in it).
You can try creating a flask App.
Just do a pip install Flask and try the code below
from flask import Flask
import flask
import json
from flask import Response
app = Flask(__name__)
#app.route('/test',methods=['GET'])
def test():
'''
GET: Receives the request in /test route and returns a response containing {"response": [1,2,3]}
'''
my_list = [1,2,3]
resp = Response(response=json.dumps({"response": my_list}), status=200, mimetype='application/json')
return resp
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8082)
Then to test your app from your browser accessing
localhost:8082/test
or also through some app like postman
I would suggest looking into something like React for creating the UI. This way your UI would only make calls to your Flask server.

PhantomJS for Flask application

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

AngularJS with python flask test fails

i'm learning to use python flask to complement angularJS. This is what i have on flask:
#!flask/bin/python
from flask import Flask, jsonify
app = Flask(__name__)
#app.route('/hola', methods=['GET'])
def get_tasks():
x="pepepepep"
return jsonify({'msj': x})
if __name__ == '__main__':
app.run(debug=True)
when i open in my browser:
http://127.0.0.1:5000/hola
i do indeed see the json object with that random message.
Now, when i go to angularJS, this is what i have on the controller:
function ControladorPrueba($scope,$http) {
$scope.mensaje="i";
$scope.ObtenerMsj= function(){
$http.get('http://localhost:5000/hola')
.success(function(data){
$scope.mensaje=data.msj;
})
.error(function(data,status){
$scope.mensaje = status;
});
};
}
The problem is that when this function is executed, the get always go on .error(...), any ideas of why this happens even when the service in flask works well when opened on the browser? am i missing something?
Any help appreciated. Thanks!
I suspect that this may be due to the Same-origin policy. If you're running your Flask app on localhost, and if you're serving your Angularjs files separately (for example, using the file:/// protocol), then the browser will actually forbid your Angular code from talking to the webservice for security reasons.
If this is the case, you have two solutions. You can either start serving your HTML/CSS/Javascript files from your Flask app, or by using something like Flask-Cors to explicitly set your server to allow external requests.

A Most Frustrating Issue Between App Engine and the Twitch.tv API

I'll make this as short and as clear as I can.
I have a simple application making a call to the twitch.tv api:
Example:
https://api.twitch.tv/kraken/streams/nl_kripp
After it makes the call, it returns the data, (you could see that data if click the link above).
Ok so on to the issue. Here is my simple application created to just return that data on a web page:
import webapp2
import urllib2
from google.appengine.api import urlfetch
class MainHandler(webapp2.RequestHandler):
def get(self):
url = ('https://api.twitch.tv/kraken/streams/nl_kripp')
result = urlfetch.fetch(url)
self.response.out.write(result.content)
app = webapp2.WSGIApplication([('/', MainHandler)],
debug=True)
When I run this application on my local machine, I see the returned data and everything is fine. However, when I deploy the application, I don't see any data at all.
That exact application is deployed at this URL:
http://urltestingsite.appspot.com/
A few people from app engine as well as twitch have tried to figure this out, and have had no luck at all. Please help me!!!
EDIT:
This is the same app, however making a call to another streaming sites API (own3d) and it works perfectly even when deployed:
import webapp2
import urllib2
class MainHandler(webapp2.RequestHandler):
def get(self):
url = ('http://api.own3d.tv/liveCheck.php?live_id=10588')
contents = urllib2.urlopen(url)
self.response.out.write(contents.read())
app = webapp2.WSGIApplication([('/', MainHandler)],
debug=True)
I don't know anything about these particular sites, but it isn't uncommon for sites to blacklist either by user agent or by IP address, possibly because of some prior bad actor. If you're getting results when developing but not when deployed, I'd suspect the latter. Have you contacted the site?

Categories