The Python code will not style - python

I can't get the css file in the folder to style. I have the file in the correct folder. Is it something to do with my indenting? I have no idea was is going on. The python code compiles and wors but the look isn't there and the page print plain.
import webapp2
class MainHandler(webapp2.RequestHandler):
def get(self):
#web page sections
form_head='''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<title>Gamers R' Us Subscribing</title>
</head>
<body>'''
form_body='''
<div class="maincontainer">
<h1>Welcome to Gamers R' Us!</h1>
<div id="bgimg">
<p>Gamers R' Us is a blog that talks and reviews video games daily. This form services as a way for users to receive emails based apon your preferred gaming system and preferred genre of game.</p>
<div id="formbox">
<h2>Subscribe Today!</h2>
<form method="GET">
<label>Full Name: </label><input type="text" name="name" placeholder=" John Doe"/><br>
<label>Email: </label><input type="text" name="email" placeholder=" me#domain.com"/><br>
<input type="checkbox" name="subscribe" value="yes" checked>Subscribe for gaming updates and more!<br>
<label>Select the gaming system you prefer:</label><br>
<select name="system" class="selectbox">
<option value="ps4">Playstation 4</option>
<option value="xbone">Xbox One</option>
<option value="wiiu">Wii U</option>
<option value="pc">PC Gaming</option>
</select><br>
<input type="radio" name="genre" value="FPS">First Person Shooter.<br>
<input type="radio" name="genre" value="MOBA">Multiplayer Online Battle Arena.<br>
<input type="radio" name="genre" value="RPG">Role-Playing Game.<br>
<input type="radio" name="genre" value="RTS">Real Time Strategy.<br>
<input type="radio" name="genre" value="Other">Other Genre.<br>
<input type="submit" class="subbtn" value="Done" />
</form>
</div>
</div>
</div>'''
form_foot='''
</body>
</html>'''
#if GET is requested it should display on next screen.
#else should load page.
if self.request.GET:
name= self.request.GET['name']
email= self.request.GET['email']
system= self.request.GET['system']
subscribe= self.request.GET['subscribe']
genre= self.request.GET['genre']
#displays form information submitted by user.
self.response.write(form_head + "<div class='maincontainer'>" +
'<h1>Thanks for Subbing!</h1>' +
'<div id="infobox">' +
'<h2></h2>' +
"Name: "+name+"<br />" +
"Email: "+email+"<br />" +
"Preferred System: "+system+"<br /> " +
"Preferred Genre: "+genre+
'</div>' +
'</div>' +
form_foot)
#Will display error. ** PLACE HOLDER **
else:
self.response.write(form_head + form_body + form_foot)
# Do not touch this.
app = webapp2.WSGIApplication([('/', MainHandler)], debug=True)

I Wager that if you use Firebug or another browser-based web app debugger, you will find that it failed to load the css/style.css resource. And then you will look at your code and realize that, even though you put style.css in a folder called css, you have configured only one URI for the server...for the / URL.
When you provide a route for /css/style.css and a corresponding handler, then the stylesheet will start to be loaded, and the HTML will be styled.

Related

Inserting data into an Oracle database from a form in Python Flask

I have a Python code.
import cx_Oracle
import re
from flask import Flask, render_template, request, url_for, redirect
app = Flask(__name__)
app.config['SECRET_KEY'] = 'd369342136ecd032f8b4a930b6bb2e0e'
#app.route('/add')
def edited():
connect = cx_Oracle.connect("********", "********", "******/XE")
cursor = connect.cursor()
cod_ed = request.form['cod_ed']
nome_ed = request.form['nome_ed']
endereco = request.form['endereco']
telefone = request.form['telefone']
cidade = request.form['cidade']
execute = """INSERT INTO editor VALUES
(:cod_ed, :nome_ed, :endereco, :telefone, :cidade)"""
cursor.execute(execute, {'cod_ed':cod_ed, 'nome_ed':nome_ed, 'endereco':endereco, 'telefone':telefone, 'cidade':cidade})
connect.commit()
#app.route('/', methods=['GET', 'POST'])
def add_data():
return render_template('forms.html')
#app.route('/post_data', methods=['GET','POST'])
def post_data():
return redirect(url_for('edited'))
if __name__ == "__main__":
app.run(host = 'localhost', port = 8000, debug=True)
And its html correspondante:
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous">
</script>
<title>Base de dados</title>
</head>
<body>
<form methods="POST" action="/post_data">
<div class="col-lg-2">
<div class="form-group">
<label for="element-1" >Codigo:</label>
<input id="cod_ed" name="cod_ed" type="text" class="form-control" placeholder="Codigo"/>
<label for="element-2" >Nome:</label>
<input id="nome_ed" name="nome_ed" type="text" class="form-control" placeholder="Nome"/>
<label for="element-3" >Endereço:</label>
<input id="endereco" name="endereco" type="text" class="form-control" placeholder="Endereço"/>
<label for="element-4" >Telefone:</label>
<input id="telefone" name="telefone" type="text" class="form-control" placeholder="Telefone"/>
<label for="element-5" >Cidade:</label>
<input id="cidade" name="cidade" type="text" class="form control" placeholder="Cidade"/>
<input class="btn btn-info" type="submit" value="Enter">
</div>
</div>
</div>
</form>
</body>
</html>
I'm relatively new to Flask and Python in general. When I run the forms, they get displayed, but when I try to insert them into the database, I get this:
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'cod_ed'
What exactly is causing it and how do I fix it?
When posting to /post_data endpoint the browser recieves a redirection code, and then gets /add without posting any data, provoking a key error.
You are fetching form elements at the wrong place. You should do the database insertion logic inside /post_data and redirect to /add afterwards.
Here you are posting the form data to /post_data and redirect it to /add so the edited function will not be able to access the request object containing the form data. So just change the form action to /add to make it work correctly.

Flask/Python 3 internal server error 500 when posting from html form

I'm new to Python & Flask and trying to set up a very basic script that takes information submitted from a form and posts it to a new page (I know, very simple right?)
I'm having limited success and can't figure out what the problem is here. It's working when I have 2 out of the 4 form fields selected in the python file:
name=request.form['name']
age=request.form['age']
This works fine and does what I expect it to do - Renders the output.html page containing 'name' & 'age'
but as soon as I try to add any more, I'm getting an internal server error (500), even through I'm copying & pasting the exact same code and only changing the variables (i.e 'number' & 'feeling') - In both the .py file and the input & output html files.
Heres the code..
Python code:
(The input form is on the /input/ page. "input_1" renders the output.html file)
from flask import Flask, render_template, request, url_for, redirect
from dbconnect import connection
from flask_debugtoolbar import DebugToolbarExtension
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'kuywergiukrewgkbyuwe'
toolbar = DebugToolbarExtension(app)
app.config.update(TEMPLATES_AUTO_RELOAD = True)
#app.route('/')
def homepage():
return render_template ("main.html")
#app.route('/input/')
def input():
return render_template ("input.html")
#app.route('/input/', methods=["POST"])
def input_1():
name=request.form['name']
age=request.form['age']
number=request.form['number']
feeling=request.form['feeling']
return render_template('output.html', name = name, age = age, number = number, feeling = feeling)
if __name__ == "__main__":
app.run()
The input.html file:
(Contains the input form)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>devserver</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap.css") }}">
<link rel="shortcut icon" href="{{ url_for("static", filename="favicon.ico") }}">
</head>
<body>
<div class="container">
<div class="col">
<h2>Input form</h2>
<br>
<div class="form-group" >
<form method="post" action="{{ url_for('input') }}">
<label for="InputForm">Name</label>
<input type="text" name="name" class="form-control"/>
<label for="InputForm">Age</label>
<input type="text" name="age" class="form-control"/>
<label for="InputForm">Number</label>
<input type="text" name="number" class="form-control"/>
<label for="InputForm">Feeling</label>
<input type="text" name="feeling" class="form-control"/>
<br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</body>
</html>
The output.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>devserver</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap.css") }}">
<link rel="shortcut icon" href="{{ url_for("static", filename="favicon.ico") }}">
</head>
<body>
<div class="container">
<div class="col">
<h2>Output form</h2>
<br>
<div class="form-group" >
<form>
<h3>Output 1</h3>
<P>Your name is = {{name}}</p>
<h3>Output 2</h3>
<P>Your age is = {{age}} </p>
<h3>Output 3</h3>
<P>Your number is = {{number}}</p>
<h3>Output 4</h3>
<P>Your feeling is = {{feeling}} </p>
</form>
</div>
</div>
</div>
</body>
</html>
I cant understand why it works with only 2. When I comment out the following it works fine:
#app.route('/input/', methods=["GET","POST"])
def input():
name=request.form['name']
age=request.form['age']
#number=request.form['number']
#feeling=request.form['feeling']
return render_template('output.html', name = name, age = age) #number = number, feeling = feeling)
It's probably something quite obvious but I just can't see it.
Thanks for the help!
You usually use url_for when you have to generate urls. I would rather not complicate matter when I have to pass multiple parameters.What I would do is just this :
<form method="post" action="/input">
and in the app file :
#app.route('/input', methods=["POST"])
def input_1():
name=request.form['name']
age=request.form['age']
number=request.form['number']
feeling=request.form['feeling']
return render_template('output.html', name = name, age = age, number = number, feeling = feeling)
But if you really wanna generate urls then put the function you want to generate url for and also pass the arguments .
<form method="post" action={{url_for('input_1',name=name)}}>
and then call funtion input_1 like this:
#app.route('/input/<name>') #you can add parameters as per your wish
def input_1(name):
...
...

How to get contents from a local text file to print on individual lines in a html template (Python/Flask)

screenshot of the outputI'm looking to get posts from a user to post on individual lines. At the moment I take in a name, email and comment, pass it to the app.py file and store it to a text file. I return a name, email, comment and the time of the comment. When I read the file and pass in back to the html template the posts display one after the other (see the screenshot included), and im trying to have them display one below each other. f.write("\n") results in the actual text file skipping a line however this does not occur in the template.
form_action.html
<html>
<div align = "center">
<body style="background-color: #3DC247;">
<head>
<title>Conor McGregor</title>
</head>
<body>
<div align = "center">
<h1 style="font-family:verdana;">I AM EL CHAPO</h1>
<div align = "center">
<h2 style="font-family:verdana;">YOU'LL DO NUTIN.</h2>
<div align = "center">
<h2 style="font-family:verdana;">Disscusion Page</h2>
<body>
<div id="container">
<div class="title">
<h3 style="font-family:verdana;">Please fill in your details
below and your comment to join the discussion</h3>
</div>
<div id="content">
<form method="post" action="{{ url_for('hello') }}">
<label for="yourname" style="font-family:verdana;">Please
enter your name:</label>
<input type="text" name="yourname" /><br /><br>
<label for="youremail" style="font-family:verdana;">Please
enter your email:</label>
<input type="text" name="youremail" /><br /><br>
<label for="yourcomment"style="font-family:verdana;">Please
enter your comment:</label>
<input type="textarea" name="yourcomment" rows="4" cols="50">
<input type="submit" /><br>
</form>
</div>
</div>
</div>
</div>
<div id="container">
<div class="title">
<h1 style="font-family:verdana;"><p>Comments</p></h1>
</div>
<div id="content">
{{details}}
</div>
</div>
</body>
</html>
app.py
from flask import Flask, render_template, request, url_for
import time
import datetime
# Initialize the Flask application
app = Flask(__name__)
# Define a route for the default URL, which loads the form
#app.route('/')
def form():
return render_template('form_submit.html')
#app.route('/hello/', methods=['POST','GET'])
def hello():
global time
name=request.form['yourname']
email=request.form['youremail']
comment=request.form['yourcomment']
comment_time=time.strftime("%a-%d-%m-%Y %H:%M:%S")
f = open ("user+comments.txt","a")
f.write(name + ' ' + email + ' ' + comment + " " + comment_time)
f.write('\n')
f.close()
with open("user+comments.txt", "r") as f:
details = f.read()
f.close()
return render_template('form_action.html', details = details, name=name,
email=email, comment=comment, comment_time=comment_time)
if __name__ == '__main__':
app.run(debug=True)
HTML does not know what \n is. You can fix this in two ways.
Convert str details to list details
details = f.read().split('\n')
This converts the str object to list object. You could print it in your template using
{% for detail in details %}
{{detail}}
{% endfor %}
Replace \n with <br>
details = f.read().replace('\n','<br>')
and then print it as {{ details|safe }} in form_action.html.
It is important that you use the safe filter. The <br> would be escaped without it and rendered as simple text.

How do I recover the address server of user, put it in variable and execute it in command line

scriptInfo.py
import os, sys, platform, webbrowser
def main()
template = open('scriptHmtl.phtml').read()
scriptHtml.phtml
<html>
<head>
</head>
<body>
<h2><center> welcome </center></h2>
<br/><br/><br/>
...
variables
..
<form name="sendData" method="get" action="http://localhost:8000/cgi/scriptGet.py">
Name: <input type="text" name="n"><br/><br/>
First Name: <input type="text" name="fn"/><br/><br/>
Mail: <input type="text" name="ma"/><br/><br/>
Address: <input type="text" name="add"/> <br/><br/>
<input type="submit" value="OK"/>
</form>
Instead of action="http://localhost:8000/cgi/scriptGet.py", there must be a variable which contain the code to recover the server address, but I don't want how to do it.
With HTML forms you can just ignore the server and go straight to the script.
For example like
<form name="sendData" method="get" action="cgi/scriptGet.py">

how to split python file into python and html file

I am trying to make a python file into a python and html files. The code i have is basically from the python guestbook example but i want to have a html file serve the uses browser. the code i have works right now but when i add the javascript at the bottom i get an error This code is at ceemee11111.appspot.com
import cgi
import datetime
import urllib
import webapp2
from google.appengine.ext import db
from google.appengine.api import users
class Greeting(db.Model):
"""Models an individual Guestbook entry with an author, content, and date."""
author = db.StringProperty()
content = db.StringProperty(multiline=True)
content2 = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
def guestbook_key(guestbook_name=None):
"""Constructs a Datastore key for a Guestbook entity with guestbook_name."""
return db.Key.from_path('Guestbook', guestbook_name or 'default_guestbook')
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
guestbook_name=self.request.get('guestbook_name')
greetings = db.GqlQuery("SELECT * "
"FROM Greeting "
"WHERE ANCESTOR IS :1 "
"ORDER BY date DESC LIMIT 3",
guestbook_key(guestbook_name))
self.response.out.write("""
<form action="/sign?%s" method="post">
<div id="container" style="width:800px">
<div id="header" style="background-color:#FFA500;">
<h1 style="margin-bttom:0;">Main Title</h1></div>
<div id="Con0" style="background-color:#FFD700;
height:200px;width:200px;float:left;">
<b>Menu</b><br>
HTML<br>
CSS<br>
<p id="demo1"></p><br>
JavaScript</div>
<div id="content" style="background-color:#EEEEEE;height:200px;width:600px;float:left;">
Content goes here</div>
</div>
<button onclick="myFunction()">Try it</button>
</form>
</body>
</html>""")
self.response.out.write("""
<form action="/sign?%s" method="post">
<div id="dataImput"
<div><textarea name="content" rows="1" cols="10"></textarea></div>
<div><textarea name="content2" rows="1" cols="10"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</div>
</form>
<hr>
<form>Guestbook name: <input value="%s" name="guestbook_name">
<input type="submit" value="switch"></form>
</body>
</html>""" % (urllib.urlencode({'guestbook_name': guestbook_name}),
cgi.escape(guestbook_name)))
class Guestbook(webapp2.RequestHandler):
def post(self):
# We set the same parent key on the 'Greeting' to ensure each greeting is in
# the same entity group. Queries across the single entity group will be
# consistent. However, the write rate to a single entity group should
# be limited to ~1/second.
guestbook_name = self.request.get('guestbook_name')
greeting = Greeting(parent=guestbook_key(guestbook_name))
if users.get_current_user():
greeting.author = users.get_current_user().nickname()
greeting.content = self.request.get('content')
greeting.content2 = self.request.get('content2')
greeting.put()
self.redirect('/?' + urllib.urlencode({'guestbook_name': guestbook_name}))
app = webapp2.WSGIApplication([('/', MainPage),
('/sign', Guestbook)],
debug=True)
#<script>
#function myFunction()
#{
#document.getElementById("demo1").innerHTML="test";
#}
Thankyou for your time.
Dan
Given that you're clearly using GAE, what you are looking to do is outlined here.
First, move your html to separate files. We'll start with the html from the oddly freefloating self.response.out.write:
"""
<form action="/sign?%s" method="post">
<div id="dataImput"
<div><textarea name="content" rows="1" cols="10"></textarea></div>
<div><textarea name="content2" rows="1" cols="10"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</div>
</form>
<hr>
<form>Guestbook name: <input value="%s" name="guestbook_name">
<input type="submit" value="switch"></form>
</body>
</html>""" % (urllib.urlencode({'guestbook_name': guestbook_name}),
cgi.escape(guestbook_name))
This belongs in a separate file we'll call myhtml.html. Second, we then are going to go through and using the Django templating system instead of %s and Python string formatting. So first, we're going to replace the %s with template-friendly fields surrounded by {{ }}, giving us:
"""
<form action="/sign?{{ guestbook_name }}" method="post">
<div id="dataImput"
<div><textarea name="content" rows="1" cols="10"></textarea></div>
<div><textarea name="content2" rows="1" cols="10"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</div>
</form>
<hr>
<form>Guestbook name: <input value="{{ guestbook_name|escape }}" name="guestbook_name">
<input type="submit" value="switch"></form>
</body>
</html>"""
Note that we were able to use the escape template filter, which is what comes after the |, to escape the value we're getting from guestbook_name.
Finally, we load the html and pass it the arguments we need:
self.response.out.write(template.render('myhtml.html', {'guestbook_name': guestbook_name}))
I think your code will really benefit from separating the HTML from the Python code.
You can do that by writing an html template and use jinja2 (which comes with google appengine) to generate the html. There are instructions on how to do that here. The JavaScript would go in the HTML template, not in the Python code.

Categories

Resources