So I'm very new to all of this but I will try to tell you what question I have.
I'm trying to create a simpel wiki API using python, bottle and .txt since this is my assignment. I wrote my question further down, very thankful for quick help.
This is my .py:
from bottle import route, run, template, request, static_file, redirect
def read_articles_from_file():
articles = []
try:
my_file = open("wiki/articles.txt", "r").close()
content = my_file.read()
for article in content.slpit("/"):
if article != "":
articles.append(article)
return articles
except:
my_file = open("wiki/articles.txt", "w").close()
return articles
#route("/")
def index():
articles_from_file = read_articles_from_file()
return template("./static/index.html", articles = articles_from_file)
#route('/addera', method="POST")
#route('/addera', method="GET")
def save_article():
title = request.forms.get("title")
text = request.forms.get("text")
my_file = open("wiki/articles.txt", "a")
my_file.close()
redirect("/")
#route('/addera')
def show_save_article():
return template("./static/index.html")
#route('/<filename>.css')
def stylesheets(filename):
return static_file('{}.css'.format(filename), root='static')
if __name__ == '__main__':
run(host='localhost', port=8080, debug=True, reloader=True)
else:
print("Något gick fel")
This is my html for index:
<!doctype html>
<html lang="sv">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Wiki</title>
</head>
<body>
<div class="header">
<div class="container">
<h1 class="header-heading">Inlämning 5 Wiki</h1>
</div>
</div>
<div class="nav-bar">
<div class="container">
<ul class="nav">
<li>Visa alla artiklar</li>
<li>Lägg till artikel</li>
</ul>
</div>
</div>
<div class="content">
<div class="container">
<div class="main" id="artiklar">
<h2>Basic wiki</h2>
<hr>
<h3>Alla artiklar</h3>
<ul class="list-unstyled">
% for article in articles:
<li>{{ article }}</li>
% end
</ul>
<hr>
</div>
</div>
</div>
</div>
<div class="footer">
<div class="container">
© Copyright 2017
</div>
</body>
</html>
Question:
Why do I get this error?
screen dump
You have a route for index ("/") and addera ("/addera"). In your index route, you are passing the articles to the template. You are not passing the articles in the addera route which is causing a bad reference in the template.
Related
I am trying to create youtube video downloader application using pytube and flask. All is done, except that a want to call pytube's stream download method from within the html script tag. How can i do it.
Here's my flask code
from flask import Flask, render_template, request
from pytube import YouTube
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html", data=None)
#app.route("/download", methods=["POST", "GET"])
def downloadVideo():
if request.method == "POST":
url = request.form["videourl"]
if url:
yt = YouTube(url)
title = yt.title
thumbnail = yt.thumbnail_url
streams = yt.streams.filter(file_extension='mp4')
data = [title, thumbnail, streams, yt]
return render_template("index.html", data=data)
if __name__ == "__main__":
app.run(debug=True)
and here's my html code
<!DOCTYPE html>
<html>
<head>
<title> Youtube Downloader </title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="stylesheet" href="static/css/style.css">
</head>
<body>
<div class="main">
<div class="header">
<div>
<img src="static/img/icon.png" width="48" height="48">
<h2> Youtube Downloader </h2>
</div>
<div>
<p> Convert and download youtube videos </p>
<p> in MP4 for free </p>
</div>
</div>
{% if not data %}
<div class="dform">
<form action="http://127.0.0.1:5000/download", method="POST">
<div class="inputfield">
<input type="input" name="videourl" placeholder="Search or Paste youtube link here" autocomplete="off">
<button type="submit"> Download </button>
</div>
</form>
</div>
{% else %}
<div class="videoinfo">
<img src="" class="thumbnail">
<h2> {{data[0]}} </h2>
</div>
<div class="quality">
<select id="streams">
{% for stream in data[2][:3] %}
<option value="{{stream.itag}}"> {{stream.resolution}} </option>
{% endfor %}
</select>
</div>
{% endif %}
</div>
<script type="text/javascript">
const image = document.querySelector(".thumbnail");
const select = document.querySelector("select");
let url = `{{data[1]}}`;
if (image) {
image.src = `${url}`;
window.addEventListener('change', function() {
var option = select.options[select.selectedIndex].value;
console.log(option);
{% set stream = data[3].get_by_itag(option) %}
{% stream.download() %}
});
}
</script>
</body>
</html>
I am trying to download the video using itag when a user clicks an option in the select element by using pytube get_by_itag() method.
From what I understand you want to do two things. You want to create a route on your flask app that will let serve up the youtube video based on an itag, and you want to be able to call that route from javascript.
This answer shows how to create a route to download the video.
To call a url that starts a file download from javascript you'll need to use the fetch method and open that link into an iFrame. This answer covers it.
Let me know if that covers your question.
Let me explain my situation. I am making a note app using flask and HTML. I want it to be so that when you click on one of the links, it takes you to a link with the title, but it isn't working! I am using ArangoDB.
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{welcome}}</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.1/css/bulma.min.css">
</head>
<body>
<section class="section has-text-centered">
<h1 class="title is-2">Hi {{username}}!</h1>
Create a note
Log out
</section>
<section>
<ul>
{% for note in notes %}
<li>
<a class="button is-light is-fullwidth" href="/{{note.title}}">{{note.title}}</a>
</li>
{% endfor %}
</ul>
</section>
</body>
</html>
and here is the relevant python code:
#app.route("/notes")
def notes_page():
global notes
notes = db.collection("Users")[username]["notes"]
if username != "":
return render_template("notes.html", username=username, notes=notes, welcome=welcome)
else:
return redirect(url_for("home"))
try:
for i in notes:
url = "/" + i["title"]
#app.route(url)
def view_note():
return render_template("view.html", title=i["title"], note=i["note"])
except NameError:
pass
I run the code and I clicked a link for a test note I created, and when I was redirected, it showed the 404 error message saying the link wasn't found. Can you please help me fix this? Thanks
When I try to add a new task on my website I get the message "POST /templates/todo" Error (404): "Not found" and cannot find what is wrong with the code. Can anyone help me figure it out? It was done on cs50ide software. If anyone could inform me whether I am able to create a functioning link for my website (I use python, flask, html and css) I would be very grateful! Thank you so much
add.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/css/styles.css" rel="stylesheet">
<title>
Add a New Task :)
</title>
</head>
<body>
<h1 class = "aligncenter">
<img class = "img1" src = "/static/images/logocarol.jpg" alt = "Logo" height = "200" width = "550"/>
</h1>
<h1 class="centergeneral fontsize">
Add any goals, dreams and aspirations you might have here:
</h1>
<form class="aligncenter" action="todo" method="POST">
<input id="task" name="task" type="text" placeholder="New Task :)">
<input id="submit" type="submit" disabled>
</form>
<script>
document.querySelector('#task').onkeyup = function(){
if (document.querySelector('#task').value === ''){
document.querySelector('#submit').disabled = true;
} else {
document.querySelector('#submit').disabled = false;
}
}
</script>
<form action="/">
<button type="submit" id = "back" class="btn btn-info margin"> BACK TO HOMEPAGE </button> <br> <br>
</form>
<form action="todo">
<button type="submit" id = "back" class="btn btn-outline-info margin"> BACK TO TO DO LIST </button> <br> <br>
</form>
</body>
todo.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/css/styles.css" rel="stylesheet">
<title>
To Do List! :)
</title>
</head>
<body>
<h1 class = "aligncenter">
<img class = "img1" src = "/static/images/logocarol.jpg" alt = "Logo" height = "200" width = "550"/>
</h1>
<h1 class="fonts centergeneral"> To Do List </h1>
<h2 class="fs-4 centergeneral"> What I Want to Achieve: </h2> <br>
<ul class="listcenter">
<script>
{%for todo in todos%}
<li> {{ todo }} <input type="checkbox" id="checkbox1"> </li>
{%endfor%}
</script>
</ul>
<a class="btn btn-outline-info margin" href = "add"> Add a New Task</a>
<a class="btn btn-outline-info" href = "clear"> Clear Tasks </a> <br>
<div class="backbuttons">
<form action="/">
<button type="submit" id = "back" class="btn btn-info"> BACK TO HOMEPAGE </button> <br> <br>
</form>
</div>
application.py code:
from flask import Flask, render_template, send_from_directory, request, redirect, session
from flask_session import Session
from cs50 import SQL
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/f1inschools')
def f1():
return render_template('f1inschools.html')
#app.route('/pdwt')
def pdwt():
return render_template('pdwt.html')
#app.route('/pros')
def pros():
return render_template('pros.html')
#app.route('/bookrecommendations')
def books():
return render_template('bookrecs.html')
#app.route('/todolist')
def todo():
if "todos" not in session:
session["todos"] = []
return render_template('todo.html', todos=session["todos"])
#app.route('/clear')
def clear():
return redirect("/todolist")
session["todos"] = []
#app.route('/add', methods=["GET", "POST"])
def add():
if request.method == "GET":
return render_template("add.html")
else:
todo = request.form.get("task")
session["todos"].append(todo)
return redirect("/todolist")
The function for adding tasks is at app.route("/add",methods=["GET","POST"]), but your form in the HTML has action="todo", so your form tries to send data to /todo which is nonexistent. To fix, simply change action="todo" to action="add".
While loading in my flask app I'm getting an internal server 404 GET error. The files that it claims are missing are exactly where they are listed not to be.
127.0.0.1 - - [06/Sep/2020 08:05:28] "GET /static/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 404 -
127.0.0.1 - - [06/Sep/2020 08:05:28] "GET /static/bootstrap/css/bootstrap.min.css.map HTTP/1.1" 404 -
127.0.0.1 - - [06/Sep/2020 08:05:28] "GET /static/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 404 -
I have my app.run() at the end of my app.py so it's not that.
I'm using a main bootstrap template HTML file that all other HTML files extend from. This is the only place my code loads the 'missing js files. Here it is(base.html):
<!DOCTYPE html>
<html lang="en">
<head>
{%block head%}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<!-- Bootstrap core CSS -->
<link href="{{ url_for('static', filename='bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
<!-- Custom styles for this template -->
<title>{%block title%}{{title1}}{%endblock%}</title>
{%endblock%}
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="#">{{title1}}</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="{{url_for('main_timeline')}}">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item active">
<!--{% if current_user.is_authenticated %}
<a class="nav-link" href="{{url_for('dashboard')}}">{{ current_user.username }}
<span class="sr-only">(current)</span>
</a>
{% else %}
<a class="nav-link" href="{{url_for('login')}}">Log In
<span class="sr-only">(current)</span>
</a>
{% endif %}-->
<a class="nav-link" href="{{url_for('login')}}">Log In
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="{{url_for('signup')}}">Signup
<span class="sr-only">(current)</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
{%block content%}
{%endblock%}
</div>
<div id="footer">
{% block footer %}
<footer class="py-5 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">© Copyright 2020 by Fizzy Bubalech.</p>
</div>
{% endblock %}
</div>
<!-- Bootstrap core JavaScript -->
<script src="{{url_for('static', filename = 'jquery/jquery.slim.min.js') }}"></script>
<script src="{{url_for('static' , filename = 'bootstrap/js/bootstrap.bundle.min.js') }}"></script>
</body>
</html>
Here is my app.py file:
#All imports for this file
#Imports for the flask libraries
from flask import Flask,flash
from flask import render_template ,redirect , url_for
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_bootstrap import Bootstrap
#Imports from the local file databases.py
from databases import get_all_posts , get_post , get_user , add_user
#Imports for the local file forms.py
from forms import Login_form , Register_form
#imports for the werkzeug Library
from werkzeug.security import generate_password_hash, check_password_hash
#imports for os commands
import os
#init app setup
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
Bootstrap(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
#setup user loader
#login_manager.user_loader
def load_user(user_id):
return get_user(int(user_id))
#login page function and route
#app.route('/login', methods=['GET', 'POST'])
def login():
form = Login_form()
if form.validate_on_submit():
user = get_user(form.username.data)
if user:
if check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
print("Login Successful")
return redirect(url_for('dashboard'))
print("Login Failed")
return None
#return '<h1>' + form.username.data + ' ' + form.password.data + '</h1>'
return render_template('login_page.html', form=form,title1 = "Login")
#main page timeline with all posts function and route
#app.route('/')
def main_timeline():
return render_template('main_timeline.html',posts = get_all_posts(),title1 = "The Timeline")
#signup page function and route
#TODO_test sigup
#app.route('/signup', methods=['GET', 'POST'])
def signup():
form = Register_form()
if form.validate():
hashed_password = generate_password_hash(form.password.data, method='sha256')
add_user(form.username.data, form.email.data, hashed_password)
return redirect(url_for('dashboard'))
#return '<h1>' + form.username.data + ' ' + form.email.data + ' ' + form.password.data + '</h1>'
return render_template('signup_page.html', form=form,title1 = "Sign Up")
#??????????
#app.route('/test')
def test():
form = Login_form()
return render_template("login.html", form = form)
#user dashboard(login required) function and route
#app.route('/dashboard')
#login_required
def dashboard():
posts = get_all_posts()
for post in posts:
if post.user_id != current_user.id:
post.pop()
render_template('dashboard.html', posts = posts)
#Post page function and route
#app.route('/post:<id>')
def load_post(id):
return render_template("post_page.html",posts = [get_post(id)],title1 = get_post(id).post_name)
#run app on file complition
if __name__ == '__main__':
app.run(debug = True)
I have run out of ideas for what the issue could be so I hope someone here can help me.
Thank you and have a good day.
I'm using Python on Google App Engine as the backend for a Desktop/Mobile web app for video sharing. I'm having an issue uploading from an iPhone to the blobstore. Usually the page redirects after the upload URL is created, but this doesn't happen on the phone. Instead the browser navigates to the upload URL, but nothing is uploaded.
I can select a video to upload just fine, and if it's a long video, the phone will take awhile to navigate to the next page which seems to imply that something is being transferred, but nothing ends up in the blobstore.
Videos are uploaded with the following Python code.
class UploadPage(webapp2.RequestHandler):
def get(self):
upload_url = blobstore.create_upload_url('/uploadvideo')
template_values = {
'upload_url': upload_url,
}
template = JINJA_ENVIRONMENT.get_template('upload.html')
self.response.write(template.render(template_values))
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload = self.get_uploads()[0]
video = Videos(content=upload.key())
video.title = self.request.get('title')
video.description = self.request.get('description')
video.ratingDown = 0
video.ratingUp = 0
video.creator = users.get_current_user().nickname()
uniuqeIDFound = False
newID = random.randint(1000,9999)
while(uniuqeIDFound == False):
vids = db.GqlQuery("SELECT * "
"FROM Videos ")
uniuqeIDFound = True
for v in vids:
if (v.videoID == newID):
newID = random.randint(1,10000)
uniuqeIDFound = False
video.videoID = newID
db.put(video)
self.redirect('/home')
The upload page itself looks like this.
<!DOCTYPE html>
<html>
<head>
<title> Upload </title>
<meta charset="utf-8">
<link type="text/css" rel="stylesheet" href="/stylesheets/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
</head>
<body>
<div class="fill">
<div class="container">
<ul class="nav nav-tabs">
<li>Home</li>
<li class="active">Upload Video</li>
<li>Logout</li>
<li>Contact Us</li>
</ul>
<h2 class="addColor">Tribal Knowledge</h2><h3 class="addColor">Upload a Video</h3>
<form class="form-horizontal" action="{{ upload_url }}" method="POST" enctype="multipart/form-data">
<textarea placeholder="Title..." name="title" cols="50" rows="1" autofocus="autofocus" required></textarea><br>
<textarea placeholder="Description..." name="description" cols="50" rows="4" autofocus="autofocus"></textarea><br>
Upload File: <input type="file" name="file"><br> <input class="btn btn-success" type="submit" name="submit" value="Upload Video">
</form>
</div>
</div>
</body>
</html>