I have a basic web app - a blog - I am trying to create using Flask.
I am trying to use {{ url_for('static', filename='vendor/fontawesome-free/css/all.min.css') }} in my index.html to create a dynamic url. However, I am continually getting a GET request error because Jinja is not recognizing it as python code, and Flask is trying to create a url using the verbatim call.
Here is an example error:
"GET /%7B%20%7Burl_for(%22static%22,%20filename=%22vendor/bootstrap/css/bootstrap.min.css%22)%20%7D%7D HTTP/1.1" 404
The problem is not with the url_for() call or with the structure of my directory/inclusion of correct static and template folders because using
with app.test_request_context():
print(url_for('static', filename='vendor/fontawesome-free/css/all.min.css'))
in my main.py file prints the correct path.
Additionally, Jinja is properly installed and working as evidenced by the fact that {% include "header.html" %} and {% include "footer.html" %} both work because the attempts to create the urls are all in those files.
Here is my main.py
from flask import Flask,render_template, url_for
import jinja2
app = Flask(__name__)
#app.route('/')
def root():
return render_template('index.html')
with app.test_request_context():
print(url_for('static', filename='vendor/fontawesome-free/css/all.min.css'))
if __name__=='__main__':
app.run(debug=True)
Here is the relevant part of index.html
{% include "header.html"%}
<!-- Page Header -->
<header class="masthead" style="background-image: url('static/img/home-bg.jpg')">
...
</header>
<!-- Main Content -->
<div class="container">
...
</div>
{% include "footer.html"%}
Here is the footer.html :
<!-- Footer -->
<footer>
...
</footer>
<!-- Bootstrap core JavaScript -->
<script src="{{ url_for('static', filename='vendor/jquery/jquery.min.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
<!-- Custom scripts for this template -->
<script src="{{ url_for('static', filename='js/clean-blog.min.js') }}"></script>
</body>
</html>
Here is the header.html :
<!DOCTYPE html>
<html lang="en">
<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="">
<title>Clean Blog - Start Bootstrap Theme</title>
<!-- Bootstrap core CSS -->
<link href="{{ url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
<!-- Custom fonts for this template -->
<link href="{{ url_for('static', filename='vendor/fontawesome-free/css/all.min.css')}} " rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- Custom styles for this template -->
<link href="{{ url_for('static', filename='css/clean-blog.min.css')}} " rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
...
</nav>
One last note, before created the dynamic urls and doing a static reference, all the CSS/JS files rendered correctly.
Edit
The following code correctly renders the url on the page.
<h1>{{url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css', _external=True)}}</h1>
It's only when I wrap it as a string that it no longer picks it up as code.
In the content you've pasted in your question, there is a Unicode zero-width non-joiner character in between the two { markers in front of your Jinja expression. That is, if I copy this line from footer.html:
<script src="{{ url_for('static', filename='vendor/jquery/jquery.min.js') }}"></script>
And produce a hexdump from it, I see:
00000000: 2020 3c73 6372 6970 7420 7372 633d 227b <script src="{
00000010: e280 8c7b 2075 726c 5f66 6f72 2827 7374 ...{ url_for('st
00000020: 6174 6963 272c 2066 696c 656e 616d 653d atic', filename=
00000030: 2776 656e 646f 722f 6a71 7565 7279 2f6a 'vendor/jquery/j
00000040: 7175 6572 792e 6d69 6e2e 6a73 2729 207d query.min.js') }
00000050: 7d22 3e3c 2f73 6372 6970 743e 0a }"></script>.
Look at offset x10, where we see e2 80 8c; that's the UTF-8 encoding of U+200c:
>>> "\u200c".encode()
b'\xe2\x80\x8c'
If I remove those extraneous characters from your source, everything works correctly:
$ curl -s localhost:5000 | grep static
<link href="/static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/vendor/fontawesome-free/css/all.min.css " rel="stylesheet" type="text/css">
<link href="/static/css/clean-blog.min.css " rel="stylesheet">
<header class="masthead" style="background-image: url('static/img/home-bg.jpg')">
This is a test /static/foo/bar
<script src="/static/vendor/jquery/jquery.min.js"></script>
<script src="/static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/static/js/clean-blog.min.js"></script>
Related
i cannot access the text box data in the back end. i wanna use the textbox value in the backend but it says 400 badrequest. Please help me with this. i cannot see where my code went wrong.i cannot access the text box data in the back end. i wanna use the textbox value in the backend but it says 400 badrequest. Please help me with this. i cannot see where my code went wrong.
python
from flask import Flask, render_template, url_for, request,redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import tweepy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db= SQLAlchemy(app)
#app.route('/')
def index():
return render_template('home.html')
#app.route('/getlivedata', methods=['POST','GET'])
def stream():
if request.method =="POST":
rows = request.form['numtweets']
else:
return render_template('home.html')
if __name__ == "__main__":
app.run(debug=True)
html
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - Navigation PageDesign/Lesson</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="sara mazal lessons">
<meta name="keywords" content="HTML, CSS, JavaScript, mazal, icons">
<meta name="author" content="Sara Mazal">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght#200;300;400;500&family=Raleway:wght#100;200;300;400;500&family=Roboto:wght#300;400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/particlesjs/2.2.3/particles.min.js"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="{{ url_for('static',filename='css/style.css') }}">
</head>
<body>
<!-- partial:index.partial.html -->
<section class="nav">
<h1>LIVE TWITTER DATA ANALYSIS</h1>
<h3 class="span loader">
<span class="m">S</spam><span class="m">E</spam><span class="m">N</spam><span class="m">T</spam><span class="m">I</spam><span class="m">M</spam><span class="m">E</spam><span class="m">N</spam><span class="m">T</spam><span class="m">A</spam><span class="m">L</spam><span class="m"> </span><span class="m">A</spam><span class="m">N</spam><span class="m">D</spam><span class="m"> </span><span class="m">C</spam><span class="m">A</spam><span class="m">T</spam><span class="m">E</spam><span class="m">G</spam><span class="m">O</spam><span class="m">R</spam><span class="m">I</spam><span class="m">C</spam><span class="m">A</spam><span class="m">L</spam> </h3>
<div class="nav-container"><a class="nav-tab" href="#tab-pwa">PWA</a><a class="nav-tab" href="#tab-graphql">GraphQL</a><a class="nav-tab" href="#tab-next">NEXT</a><a class="nav-tab" href="#tab-typescript">TYPESCRIPT</a><a class="nav-tab" href="#tab-deno">DENO</a><span class="nav-tab-slider"></span></div>
</section>
<form action="#" method="post">
<main class="main">
<section class="slider" id="tab-pwa">
<h1>PWA</h1>
<input type="text" name="numtweets">
<h3>GetLiveData</h3>
<h2>the best of both worlds...</h2>
</section>
<section class="slider" id="tab-graphql">
<h1>GraphQL</h1>
<h2>a query language for APIs</h2>
</section>
<section class="slider" id="tab-next">
<h1>NEXT</h1>
<h2>framework for Production</h2>
</section>
<section class="slider" id="tab-typescript">
<h1>TYPESCRIPT</h1>
<h2>giving you better tooling at any scale</h2>
</section>
<section class="slider" id="tab-deno">
<h1>DENO</h1>
<h2>a modern runtime</h2>
</section>
</main>
</form>
<canvas class="background"></canvas>
<!-- partial -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script><script src="{{ url_for('static',filename='js/script.js') }}"></script>
</body>
</html>
Change your form action to "/getlivedata" so it would post the data there. Also, it seems that you are using the as the way to go to the url. Use a submitnbutton instead.
I am trying to display my html files using python alone. Such as I would python code.py and I would be able to access my html at localhost:8080
html files are static files that access each other. For example, index.html directs to contact.html and all of them access css folder.
How do I open my html files so it displays it on the webpage?
below is what I have so far.
html_file = []
with open("index.html", "r") as f:
for line in f.readlines():
html_file.append(line)
Is there way to do python code.py and when I access localhost:8000 that would show me the code? and I can access each page.
here is an example html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<img class="resize" src="./pictures/logo.png" alt="logo">
<nav>
<ul class="nav-links">
<li class="active">Home</li>
<li>Contact</li>
</ul>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
$(document).on('click', 'ul li', function(){
$(this).addClass('active').siblings().removeClass('active')
})
</script>
</nav>
</header>
</body>
</html>
There's way to do so using the python web frameworks like Flask or Django. In a typical flask scenario your code would look like this:-
1) Install flask:-
pip install flask
2) Write your code.py like this:-
from flask import Flask, url_for
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('hello.html')
3) Next create a templates folder inside which put your html file which I have named it to be hello.html
templates > hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<img class="resize" src="./pictures/logo.png" alt="logo">
<nav>
<ul class="nav-links">
<li class="active">Home</li>
<li>Contact</li>
</ul>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
$(document).on('click', 'ul li', function(){
$(this).addClass('active').siblings().removeClass('active')
})
</script>
</nav>
</header>
</body>
</html>
4) Your directory structure would look like this:-
/code.py
/templates
/hello.html
5) Run python code.py and you can see your page on localhost:5000.
Problem: As the title says I am building a django project the base.html extended to homepage.html and works fine, static images appear, but home.css does not works anywhere.
Update
I have switched in the base.html
from this <link rel="stylesheet" href="{% static 'css/home.css' %}">
to this <link href="css/home.css" rel="stylesheet" />
than I have also tried this: <link rel="stylesheet" type="text/css" href="{% static 'css/home.css' %}" />
It deletes a formatting on -s that was caused by another previously used .css that has been deleted since but the formatting sticked on.
I have called this css property thickkk{color: red;}
many places in both base.html and home.html and it still not working.
I have also get the following error message if I inspect the site with/F12/consol/ 127.0.0.1/:1 Refused to apply style from 'http://127.0.0.1:8000/css/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Update ERROR message
Refused to apply style from 'http://127.0.0.1:8000/stacic/css/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Properties: Python 3.7, Bootstrap 4
settings.py
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'baseprojectfolder/static/')]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
base.html
I have created a base.html that hold the navbar and the footer.
This also has the CSS imported from a static css and also from bootstrap
It finds the static files because it imports the images that are appearing both here and in the home page
<!doctype html>
<html lang="en">
{% load static %}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="xz">
<meta name="author" content="xz">
<link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>
<link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico">
<title>Click Helps - BE PART OF THE NEW CREATION</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.3/examples/carousel/">
<!-- Bootstrap core CSS -->
<link href="/docs/4.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'css/home.css' %}">
</head>
....
<!-- Bootstrap core JavaScript ================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="/docs/4.3/assets/js/vendor/jquery-slim.min.js"><\/script>')</script>
<script src="/docs/4.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>
<!-- I have placed in the followring 3 line from bootstrap to make JS work -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
home.html
I have used the center CSS property I have created
{% extends 'applicaonfolderofmine/templates/base.html' %}
{% load static %}
{% block content %}
<main>
<body>
<div class="container">
<h1 id="about" class="center" >About</h1>
...
home.css
it can be found in "django-project/certainapplication/static/css/home.css"
.center {
margin: auto;
width: 60%;
padding: 10px;
}
Error messages in terminal
Not Found: /docs/4.3/dist/css/bootstrap.min.css
[22/Feb/2020 15:55:26] "GET /docs/4.3/dist/css/bootstrap.min.css HTTP/1.1" 404 2494
Not Found: /docs/4.3/dist/js/bootstrap.bundle.min.js
[22/Feb/2020 16:24:29] "GET /docs/4.3/dist/js/bootstrap.bundle.min.js HTTP/1.1" 404 2509
Not Found: /docs/4.3/dist/js/bootstrap.bundle.min.js
[22/Feb/2020 16:24:29] "GET /docs/4.3/dist/js/bootstrap.bundle.min.js HTTP/1.1" 404 2509
I have read the following articles but they haven't answered my question:
css for base template in django
Adding css file after all extensions css files
Django UserProfile extension
Background from CSS not working in Base.html
Django mptt, extends "base.html"
{ % extends parent _ template|default:"base.html" % } vs {% extends "base.html" %} in Django?
Django templates extending and CSS
How does Django's extends work?
As you have STATICFILES_DIRS remove STATIC_ROOT then type python manage.py collectstatic, then yes, then run your server again.
The server should respond with the correct MIME Type for JSONP application/javascript and your request should tell jQuery you are loading JSONP dataType: 'jsonp'
Please see this answer for further details ! You can also have a look a this one as it explains why loading .js file with text/plain won't work.
Disable Chrome strict MIME type checking
I want to copy all the code of an URL (http://modelseed.org/biochem/reactions/rxn00001) using Python 3.6, but I can only copy part of the code, and I don't know why.
So far, I tried with "requests" module
import requests
page = requests.get("http://modelseed.org/biochem/reactions/rxn00001")
print(page.content)
and "urllib"
import urllib.request
site = urllib.request.urlopen("http://modelseed.org/biochem/reactions/rxn00001")
print(site.read())
The part of the code with information of the "Reaction Details", like "Name", "ID" and "Abbreviation" are missing, but they are visible if I inspect the code on the developer bar of Chrome.
The code I'm able to download using the two codes above is:
<!DOCTYPE html>
<html lang="en" ng-app="ModelSEED">
<head>
<base href="/"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<meta content="IE=edge" http-equiv="X-UA-Compatible"/>
<meta content="initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<meta content="The ModelSEED is a resource for the reconstruction, exploration, comparison, and analysis of metabolic models." name="description"/>
<link href="/img/ModelSEED-favicon.png?v=2.0" rel="shortcut icon"/>
<meta content="nconrad" name="author"/>
<title>
ModelSEED
</title>
<link href="components/angular-material/angular-material.css" rel="stylesheet"/>
<link href="components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<!-- to be removed -->
<link href="components/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
<link href="icomoon/style.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
<link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"/>
<link href="build/style.css" rel="stylesheet"/>
<!--<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>-->
<script src="build/site.js">
</script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</meta>
</head>
<body>
<div style="height: 100%;" ui-view="">
</div>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-67412611-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
Anyone has any hint why the code between < div style="height: 100%;" ui-view="" > and (just after < body > and before < script >) is not downloaded?
Thank you.
It's being inserted by a javascript script, therefore, either requests nor urllib would find it, you would need to use a browser for this, you should try with selenium or PhantomJS
something like:
from selenium import webdriver
driver = webdriver.Chrome('./chromedriver')
driver.get(url)
driver.page_source
Try getting this url instead: https://www.patricbrc.org/api/model_reaction/?http_accept=application/json&eq(id,rxn00001)
I am migrating several pages over to use our site's new template. These are legacy pages, though, so they need a couple extra global js files.
I was hoping to set a legacy flag in the child page views, and then have an if check in the master template, but this didn't seem to work.
Is there a better way to do this?
The ideal approach would mean I could simply declare the global legacy scripts in one place. I don't want to have to include them on every legacy child page, which is what we're doing now.
Parent template:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=.5"/>
<title>Title</title>
<link rel="stylesheet" href="/static/css/global.css"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<%block name="page_css" />
</head>
<body>
<!-- Body -->
<div class="bc-page-wrapper">
${self.body()}
</div>
<script type="text/javascript" src="/static/globals.js"></script>
% if legacy == 1:
<script type="text/javascript" src="/static/js/legacy.js"></script>
% endif
</body>
</html>
Legacy Page Inheriting Template:
<%
legacy = true
%>
<%inherit file="/global/ko_admin_template.html" />
<div class="legacy-container">
content here
</div>