I have 2 scripts. One is my main.py script where it will call my other script to print an HTML page. The second script is html_pages.py. I'm trying to print an HTML page by importing html_pages.py and calling the welcome_page or login_page function.
Whenever I try to reach the page it says "Internal error". This was working previously when I had the login_page and welcome_page as a string stored in the main script. But it doesn't work when I try to call the function from a different script.
my main.py script contains:
#!/usr/bin/python3
import html_pages
if "HTTP_COOKIE" in os.environ :
cookie_info = os.environ["HTTP_COOKIE"]
cookies = cookie_info.split(';')
for cookie in cookies:
cookie_split = cookie.split('=')
cookie_dict[cookie_split[0].strip()] = cookie_split[1].strip()
CookieUsername = cookie_dict.get('username')
CookiePassword = cookie_dict.get('password')
CookieToken = cookie_dict.get('CSRFtoken')
#Connect to the database
import pymysql
conn = pymysql.connect(db='project2', user='algarcia1', passwd='root', host='localhost')
c = conn.cursor()
#Collect info about the user
query = "SELECT * FROM bank WHERE username='{CookieUsername}'"
c.execute(query.format(CookieUsername=CookieUsername))
conn.commit()
user = c.fetchone()
print(html_pages.welcome_page(user[0],user[3],user[4]))
else:
cookie_dict["username"] = "undefined"
cookie_dict["password"] = "undefined"
print(html_pages.login_page())
My HTML_pages.py script looks like this:
#!/usr/bin/python3
#Create a login HTML page
def login_page(status):
loginpage = """Content-Type: text/html
<!DOCTYPE html>
<!-- HTML code to send a POST request to login.py -->
<html>
<head>
<title>Safe Bank Website</title>
</head>
<body>
<form action="login.py" method="POST">
<h1>Safe Bank Website</h1>
<strong>Username:</strong><br>
<input type="text" name="username"><br>
<strong>Password:</strong><br>
<input type="text" name="password"><br>
<strong>CSRF token:</strong><br>
<input type="text" name="CSRFtoken"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>"""
print(login_page.format())
def welcome_page(username, chequings, savings):
#Create a welcome HTML page
welcomepage = """Content-Type: text/html
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {{ border: 2px solid black; text-align: left;}}
th, td {{ padding: 5px; }}
</style>
</head>
<body>
<h2>Welcome {cookie_info}!</h2>
<table style="width:100%">
<tr>
<th>Chequings</th>
<th>Savings</th>
</tr>
<tr>
<td>{chequings}</td>
<td>{savings}</td>
</tr>
</table>
Transfer money
</body>
</html>"""
print(welcome_page.format(cookie_info=username,chequings=chequings,savings=savings))
There are so many good python Web-Frameworks like Flask or Django. That make it easy so build webpages in a secure way. Especially Flask is very easy to use. Try them out and look how such frameworks do it.
In most cases it's more solid for future use to use a framework where you have a good structure.
Related
I am trying to create web application using Flask and python. I created frames in the html page by using iframe. So, I have two sections in the HTML Page now. In the top iframe, I have few input fields and submit button. And the bottom iframe, I have a blank page. So, when I hit submit button which is in top iframe, the results should be displayed in the bottom iframe. I can get results in another html page which I do not want it.
How do I get results on bottom iframe in the same html page?
Query.py:
from flask import Flask, render_template, request, redirect, url_for
import sys
import logging
app = Flask(__name__)
# Ensure that debug mode is *on*
app.debug = True
#app.route('/')
def query():
return render_template('query.html')
#app.route('/queryform')
def queryform():
return render_template('queryform.html')
#app.route('/queryform', methods=['POST'])
def queryform123():
data = request.form['f1']
dselection = request.form['dbselection']
e = mqr.a(data)
return render_template('query.html', s = e, p = dselection)
#app.route('/queryblank')
def queryblank():
return render_template('queryblank.html')
if __name__ == '__main__':
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.run(debug=True, port='5001')
Query.html
<html>
<head>
<title>Query</title>
<style>
.menu {
float:right;
width:85%;
height:35%;
}
.mainContent {
float:right;
width:85%;
height:65%;
}
</style>
</head>
<body>
<iframe class="menu" id="frame1" src="queryform"></iframe> //-- this is html page
<iframe class="mainContent" id="frame2" src="queryblank"> </iframe> //--this is another html page
</body>
</html>
Queryblank.html
<html>
<head>
<title>queryblank</title>
</head>
<body>
<center>
Query Results Window
</center>
</body>
</html>
Queryform.html
<html>
<head>
<title> query form</title>
</head>
<body>
<table width="100%" height="25">
<tr>
<td width="100%" bgcolor="#0000FF" align="center" color="#000000">
<font face="Arial Black" color="#FFFFFF">Query</font></td>
</tr>
</table>
<form name="queryform" target="bottom" method="POST">
<input type=hidden name="butn">
<td><input type=text name="f1"></td>
</table>
Database:
<SELECT NAME=dbselection>
<OPTION SELECTED>Dev
<OPTION>Prod
</SELECT>
<input type="submit" name="submit_button" value="Query Database">
</form>
</body>
</html>
This question already has an answer here:
Flask : href link to html not working
(1 answer)
Closed last year.
I'm trying to make a program to display some time and temperature numbers on a web page. I have two html templates, "index.html" and "set.html" in a "templates" directory under the main "furnace" directory. The index part works as it should when called by flask but the "set" link (to go to a page to enter a new time and date) results in a "404 Not found" error. I've stripped everything out of the Python program that isn't part of flask and displaying the html, and I still get the error. At this point, all that's left is about the same as simple examples I've found; I've compared my program to the examples and I just can't see what's going wrong. Can some sharp eyes spot my mistake?
furnace-9x.py
import time
import datetime
import RPi.GPIO as GPIO
import smbus
from gpiozero import Button
from flask import Flask, render_template
import SDL_DS3231_dev
import lcddriver
import threading
# Using a global here for simplicity in this demo
# Globals are generally bad practice, so you would maintain
# the status of "lcd_counter" in a more elegant way
# (e.g. through a shared module, through classes, etc.)
# A simple global serves the purpose for this demo
# of a flask server running in parallel to another process
# emulating some I/O, printing to the console, etc.
lcd_counter = 0
app = Flask(__name__)
#app.route("/")
def index():
print('Index')
global datetimestr, temperature
global minutes_24,minutes_30,heatOn
return render_template('index.html')
#app.route("/set")
def setTime():
print("Set time")
return render_template('set.html')
if __name__ == '__main__':
#=== Prelude ===
app.run(debug=False, host='0.0.0.0')
index.html
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {font-family:arial;
background-color: rgb(185,179,175);
text-align: left;}
table, tr {text-align: left;
font-size: 150%;
border-style: solid;}
</style>
</head>
<body>
<h1>Furnace</h1>
<table>
<tr>
<td colspan="3">{{dtstr}}</td>
</tr>
<tr>
<td>30 day: </td>
<td>{{m30}}</td>
<td>{{p30}}%</td>
</tr>
<tr>
<td>24 hour: </td>
<td>{{m24}}</td>
<td>{{p24}}%</td>
</tr>
<tr>
<td>Temp:</td>
<td> {{temper}}°F </td>
<td>Heat: {{heat}}</td>
</tr>
</table>
<p>Set time</p>
</body>
</html>
set.html
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {font-family:arial;
background-color: rgb(185,179,175);
text-align: left;}
table, tr {text-align: left;
font-size: 150%;
border-style: solid;}
</style>
</head>
<body>
<p>Enter the date and time:
<input type="text" name="datetime" size="15" maxlength="19" />
<input type="submit" value="Submit" />
</p>
</body>
</html>
The problem here is a mismatch between the link in index.html (set.html) and your route (/set).
To resolve the issue, you can update line 35 in your index.html like this:
<p>Set time</p>
The flask web server matches the route strings exactly, and not the file names of the templates. Even better, you can use the flask built in function url_for:
<p>Set time</p>
This is for my mini project which is evaluated..basically i need a GUI to show double hashing implementation. I used html and css to create my front end but i am not able to connect my back end to the front..
I've written my code in python and the front end part using HTML and CSS
double hash page in html where i need to embed my python code:
<html>
<head>
<link href='style1.css' rel='stylesheet' type='text/css'>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" href="favicon.ico" type="image/x-icon">
<!--<script src="hash.js"></script>-->
<!-- method i tried to embed my code -->
<!--<script type="text/javascript">
function runPyScript(input){
var jqXHR = $.ajax({
type: "POST",
url: "/double",
async: false,
data: { mydata: input }});
return jqXHR.responseText;}
$('#submitbutton').click(function(){
datatosend = 'this is my matrix';
result = runPyScript(datatosend);
console.log('Got back ' + result);
});
</script>-->
<!-- end of method -->
<title>DOUBLE HASHING IMPLEMENETATION</title>
</head>
<br>
<br>
<body>
<h1> DOUBLE HASHING</h1>
<!--<h3 class="probingName">Type of Probing: </h3>-->
<div id="container">
<i class="icon-home">Home</i><br>
</div>
<br>
<div id="instructions">
<p>Enter the size of the hash table:</p>
<form method="post">
<input type="text" name="size" placeholder="size" required>
<input class="btn btn-primary" type="submit" name="ENTER" value="ENTER">
</form>
</div>
<div id="content">
<br />
<!-- my pyhton code -->
<% def double_hashing(keys, hashtable_size, double_hash_value %>
<%hashtable_list = [None] * hashtable_size %>
<%for i in range(len(keys)): %>
<% hashkey = keys[i] % hashtable_size %>
<%if hashtable_list[hashkey] is None: %>
<% hashtable_list[hashkey] = keys[i] %>
<% else: %>
<% new_hashkey = hashkey%>
<%while hashtable_list[new_hashkey] is not None: %>
<%steps = double_hash_value - (keys[i] % double_hash_value) %>
<%new_hashkey = (new_hashkey + steps) % hashtable_size%>
<%hashtable_list[new_hashkey] = keys[i]%>
<%return hashtable_list %>
<% values = [26, 54, 94, 17, 31, 77, 44, 51] %>
<%=print(double_hashing(values, 21, 19))%>
<!-- end code -->
</div>
</html>
With the python package Flask, you can set up a web server with an HTML frontend and a python backend in only a few lines of code.
Here is the Flask website: http://flask.pocoo.org/
Here is a pretty basic example of a Flask server that displays a web page and you can post data to:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/', methods=['GET'])
def index():
return render_template('index.html')
#app.route('/post', methods=['POST'])
def post():
return "recived: {}".format(request.form)
if __name__ == "__main__":
app.run(debug=True)
note: for render_template to work, your HTML file must be in a folder called templates
To connect front-end with backend using python you need a backend development framework. popular in python is Django full-stack, flask micro-framework, and pyramid full stack.. create web pages in HTML using all front end technology after that put all in 1 folder but anyway you need a framework for the link. You can use API also but ultimately need a FRAMEWORK.
I am trying to get through a proxy server through python to extract some information from the website, so far I this piece of code, but it doesnt seem to be working
import requests
import BeautifulSoup
URL = 'http://proxy.library.upenn.edu/login?url=http://clients1.ibisworld.com/'
session = requests.session()
# This is the form data that the page sends when logging in
login_data = {
'pennkey': "****",
'password': "****",
'submit': 'login',
}
# Authenticate
r = session.post(URL, data=login_data)
doc = BeautifulSoup.BeautifulSoup(r.content)
print doc
edit: this is what this prints:
Gorkems-MacBook-Pro:desktop gorkemyurtseven$ python extract.py
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="HandheldFriendly" content="True" />
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=yes, minimum-scale=.5" />
<title>University of Pennsylvania Libraries Proxy Service - Login</title>
<link href="/public/proxysm.css" media="print, screen" rel="stylesheet" type="text/css" />
<script language="javascript">
function validate(){
var isgoldcard = document.authenticate.pass.value;
var isgoldcardRegxp = /00000/;
if (isgoldcardRegxp.test(isgoldcard) == true)
alert("Authentication is by PennKey only.");
}
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-982196-4']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<!--[if IE]>
<style>
table, form .limitwidth {width: 252px;}
.holdsubmit {width: 143px;}
</style>
<![endif]-->
</head>
<body onload="document.authenticate.user.focus();">
<div id="logostripe">
<div><img src="/public/librarieslogologin.gif" border="0" alt="Penn Libraries Home" /></div>
</div>
<h1>Libraries Proxy Service</h1>
<div id="holder">
<form name="authenticate" action="https://proxy.library.upenn.edu/login" method="post" autocomplete="off">
<div class="limitwidth">
<input type="hidden" name="url" value="http://clients1.ibisworld.com/" />
<script type="text/javascript">
var t = location.search;
t = t.substr(t.indexOf('proxySessionID')+15,t.indexOf('&')-16);
document.cookie="proxySessionID="+escape(t)+"; path=/; domain=.library.upenn.edu";
</script>
<table align="center" cellspacing="0" cellpadding="2" border="0">
<tr>
<td class="holdlabels"><label for="user">PennKey:</label></td>
<td><input type="text" name="user" /></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" name="pass" onblur="validate(); return false;" /></td>
</tr>
<tr>
<td></td>
<td class="holdsubmit">
<div><input type="submit" value="Login" /></div>
</td>
</tr>
</table>
</div>
</form>
<ul class="moreinfo">
<li><a class="menuitem" href="http://www.upenn.edu/computing/pennkey">PennKey information</a></li>
</ul>
<div class="notices">
The Library Proxy Service allows you to use
domain-restricted resources & services by authenticating yourself as Penn Faculty,
Student, or Staff.
</div>
<div class="alert">
Please note limitations on the use of restricted online resources.
<br /><br />
PennKey holders must be current faculty, student, or staff, have valid University PennCommunity credentials and abide by stated Restrictions On Use.
<br /><br />
In addition, users agree to the University's Appropriate Use Policy.
</div>
</div><!-- close holder -->
</body>
</html>
Here's a solution that works for me (also using Penn's proxy server):
import requests
from bs4 import BeautifulSoup
proxies = {'https': 'https://proxy.library.upenn.edu'}
auth = requests.auth.HTTPProxyAuth('[username]', '[password]')
r = requests.get('http://www.example.com/', proxies=proxies, auth=auth)
print BeautifulSoup(r.content)
The first key is that the proxy server is https, and not http (this took me far too long to figure out). Next, you must use the requests.auth.HTTPProxyAuth method for authenticating with the server. Once, you set these two vars, however, you should be able to navigate wherever you need.
I posted a question yesterday :
Redirect python script to another python script for validation of login credentials
after i was done with that bit, i had another problem related to cookies. I sent the cookies in the header from the python script code:
#Create Cookie
C= Cookie.SimpleCookie()
#take the value of usernameLogin into the variable username
username= form.getvalue('usernameLogin')
#Set-Cookie header with the usernameLogin key
C['usernameLogin'] = username
this code is in the previous python script validate.py
i want to send the cookies to the next script page1.py
this is my code for page1.py :
import cgi
import cgitb
import sqlite3
import Cookie
import os
user_name=""
user_id=""
useridDb=""
resultid=""
resultname=""
idUser=""
if os.environ.has_key("HTTP_COOKIE"):
C= Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE",""))
if C.has_key("usernameLogin"):
user_name= C['usernameLogin'].value
print user_name
form= cgi.FieldStorage()
cgitb.enable()
#Open connection
conn= sqlite3.connect("manager.db")
page1head= """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Excursions</title>
<link rel='stylesheet' type='text/css' href='/page1.css/' />
<script lang="javascript" type="text/javascript" src="/suggestions.js/"> </script>
</head><body>
<div id="container">
<div id="header">
<h1>Field Note Manager</h1>
<p class="description">Observe...Record...Save!</p>
</div>
<!-- Content Section -->
<div id="wrapper">
<!-- Main Content Section -->
<div id="content">
<h2>Excursions</h2>
<table CELLPADDING="10" ><tr><th> <strong> Location </strong> </th><th> <strong> Date </strong> </th> <th> Time </th></tr>"""
page2head="""</table>
</div>
</div>
<!-- Logout Section -->
<div id="navigation">
<input type="hidden" name="greeting"/>
<form action="http://localhost:8000/cgi-bin/logout.py">
<p><input type="submit" name="logoutBtn" value="Logout" /> </p>
</form>
</div>
<!-- Extra Section for Queries -->
<div id="extra">
<h2>Quick Links</h2>
<dl> <dd><a href="http://localhost:8000/cgi-bin/query.py"/>Query the Database</a> </dd></dl>
<dl> <dd><a href="http://localhost:8000/cgi-bin/addFieldNote.py"/>Add Field Note</a> </dd></dl>
</div>
<!-- Footer -->
<div id="footer">
<p>Copyright 42578647, 2012</p>
</div>
</div>
"""
page1foot= """
</body>
</html>
"""
print "Content_type: text/html\n\n"
print page1head
#print excursion details
cur=conn.cursor()
resultid= cur.execute("SELECT userid FROM login WHERE username=?",[user_name])
cur.fetchone()
for data in resultid:
idUser= int(data)
resultname= cur.execute("""SELECT location,excurDate,excurTime FROM excursion WHERE user=?""",[idUser])
cur.fetchall()
for record in resultname:
print"<tr><td>",record[0],"</td><td>",record[1],"</td><td>",record[2],"</td></tr>"
print page2head
print page1foot
It prints the page, but no queries are generated. Is it because the cookie has not been retrieved and parsed or is there some problem with the SELECT statement?
I found out the answer. The cookies had not been set before the header in the previous validate.py