I have been try simple python socket, I have bootstrap.min.css in the same directory of registro.html, but it's not charge style from bootstrap, registro.html, bootstrap.min.css and soket_test.py are in same directory.
I have been do request from any browser.
socket_test.py
#!/usr/bin/env python
import socket
import json
import re
def getValorArreglo(parametros, clave):
for indice in parametros:
if indice.split('=')[0] == clave:
return indice.split('=')[1]
return None
'''def setSiguienteVista(action,parametros):
if action != None and action == '/formulario':'''
host = '127.0.0.1'
port = 8791
server_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # Create a socket object
server_sock.bind((host , port)) # Bind to the port
server_sock.listen(5) # Now wait for client connection.
print ('Entering infinite loop; hit CTRL-C to exit')
while True:
# Establish connection with client.
client_sock, (client_host, client_port) = server_sock.accept()
print ('Got connection from', client_host, client_port)
request = b""
contador = 0
while not b"\r\n\r\n" in request:
request += client_sock.recv(1000) # should receive request from client. (GET ....)
client_sock.send(b'HTTP/1.0 200 OK\n')
client_sock.send(b'Content-Type: text /html\n')
client_sock.send(b'\n') # header and body should be separated by additional newline
# you can paste your 2 text field html here in the <body>
HtmlFile = open('registro.html','r')
registro = HtmlFile.read()
client_sock.send(registro)
client_sock.close()
registro.html
<!DOCTYPE html>
<html>
<head>
<title>Proyecto Sistemas Distribuidos</title>
<link rel="stylesheet" href="bootstrap.min.css">
</head>
<body>
<form method="post" action="formulario"class="form-group" >
<div class="form-row etiqueta_principal">
<label class="text-label-principal">REGISTRO DE BACHILLER ASPIRANTE</label>
</div>
<div class="form-row">
<div class="form-group col-md-3 item-div">
<label class="col-md-12 item-label" for="nombre1">Primer Nombre</label>
<input type="text" class="form-control" id="nombre1" name="nombre1" placeholder="Ingrese primer nombre"
required>
</div>
<div class="form-group col-md-3 item-div">
<label class="col-md-12 item-label" for="nombre2">Segundo Nombre</label>
<input type="text" class="form-control" id="nombre2" name="nombre2"
placeholder="Ingrese segundo nombre">
</div>
<div class="form-group col-md-3 item-div">
<div class="item-div button-div">
<button type="submit" class="btn btn-secondary">Enviar Solicitud</button>
</div>
</div>
</form>
</body>
</html>
Related
Im trying to develop an app that gets a user input (an excel spreadsheet) and then upload that information to a database depending if the user pressed option A or option B.
The issue I´m having is that when I submit and upload something and try to then click the "go back" botton and try to upload someting else, the script gives me an error.
The backend is:
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
#Read the excel that was dragged
file = request.files['file']
#Identify the survey and project switchs
survey_switch = request.form.get("switch-1")
project_switch = request.form.get("switch-2")
#Convert the file dragged into a dataframe
df = pd.read_excel(file, skiprows=3, engine='openpyxl')
if survey_switch == 'Survey' and project_switch != 'Project':
session["survey_switch"] = survey_switch
session["project_switch"] = None
connection = utils.CreateConnection(file, df)
#Insert the Survey on the file dragged
utils.CreateSurvey(file, connection, df)
return redirect(url_for('messages'))
if project_switch == 'Project' and survey_switch != 'Survey':
session["survey_switch"] = None
session["project_switch"] = project_switch
connection = utils.CreateConnection(file, df)
#Insert the Project on the file dragged
utils.CreateProject(file, connection, df)
return redirect(url_for('messages'))
if survey_switch == 'Survey' and project_switch == 'Project':
session["survey_switch"] = survey_switch
session["project_switch"] = project_switch
connection = utils.CreateConnection(file, df)
#Insert the Survey and Project on the file dragged
utils.CreateSurvey(file, connection, df)
utils.CreateProject(file, connection, df)
return redirect(url_for('messages'))
return render_template('SIMMetadata_index.html')
#Make the messages template
#app.route('/UserInterface', methods=['GET', 'POST'])
def messages():
#Make the go back
if request.method == 'POST':
session["survey_switch"] = None
session["project_switch"] = None
return redirect(url_for('index'))
return render_template('UserInterfaceMessages.html')
The frontend are:
Index page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE11">
<title>SIM Metadata</title>
<link href="../static/css/em-unity-1.6.0.min.css" media="all" rel="stylesheet" />
<script type="text/javascript" src="../static/js/vendor/svg4everybody.min.js"></script><!-
- polyfill for SVG icons -->
</head>
<body>
<!-- Banner azul del head-->
<header class="em-c-header em-c-header--blue" role="banner">
<div class="em-l-container em-c-header__inner">
<div class="em-c-header__body">
<div class="em-c-header__title-container">
<h2 class="em-c-header__title"><a href="#" rel="home" class="em-c-header__title-
link">SIM Metadata</a></h2>
</div>
</div>
</header>
<!-- la caja de drag files con el padding respectivo-->
<div class="em-u-padding">
<!-- asignar distinta clase em-is-valid si el documento insertado es valido o em-has-error
si no es valido--->
<form action="/" method="POST" enctype="multipart/form-data" autocomplete="off">
<div class="em-c-field em-c-field--file-upload ">
<label for="file" class="em-c-field__label">KDM Spreadsheet</label>
<div class="em-c-field__body">
<svg class="em-c-icon em-c-icon--large em-c-field__block-icon">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="../static/images/48/em-<body>
<!-- Banner azul del head-->
<header class="em-c-header em-c-header--blue" role="banner">
<div class="em-l-container em-c-header__inner">
<div class="em-c-header__body">
<div class="em-c-header__title-container">
<h2 class="em-c-header__title"><a href="#" rel="home" class="em-c-header__title-
link">SIM Metadata</a></h2>
</div>
</div>
</header>
<!-- la caja de drag files con el padding respectivo-->
<div class="em-u-padding">
<!-- asignar distinta clase em-is-valid si el documento insertado es valido o em-has-error
si no es valido--->
<form action="/" method="POST" enctype="multipart/form-data" autocomplete="off">
<div class="em-c-field em-c-field--file-upload ">
<label for="file" class="em-c-field__label">KDM Spreadsheet</label>
<div class="em-c-field__body">
<svg class="em-c-icon em-c-icon--large em-c-field__block-icon">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="../static/images/48/em-
icons.svg#upload"></use>
</svg>
<input type="file" name="file" id="file" class="em-c-file-upload"
placeholder="Placeholder" enctype="multipart/form-data" />
<ul class="em-c-field__list em-js-field-list">
<li class="em-c-field__item">Drag file here</li>
<li class="em-c-field__item em-c-field__item--small">Or click to choose file</li>
</ul>
</div>
<div class="em-c-field__note">The extension of the spreadsheet must be .xls or .xslx</div>
</div>
<ul class="em-c-switch-list">
<li class="em-c-switch-list__item">
<div class="em-c-field">
<div class="em-c-field__body">
<div class="em-c-switch">
<label class="em-c-switch__label" for="switch-1">
<span class="em-c-switch__toggle"></span>
<span class="em-c-switch__label-name">Upload Survey</span>
</label>
<input id="switch-1" type="checkbox" name="switch-1" value="Survey" class="em-c-
switch__input em-js-switch-trigger" >
</div>
</div>
</div>
</li>
<li class="em-c-switch-list__item">
<div class="em-c-field">
<div class="em-c-field__body">
<div class="em-c-switch">
<label class="em-c-switch__label" for="switch-2">
<span class="em-c-switch__toggle"></span>
<span class="em-c-switch__label-name">Upload Project</span>
</label>
<input id="switch-2" type="checkbox" name="switch-2" value="Project" class="em-c-
switch__input em-js-switch-trigger">
</div>
</div>
</div>
</li>
</ul>
<!-- agregar las botones de survey y project-->
<!--agregar el boton de submit -->
<div class="em-u-text-align-center">
<div class="em-c-btn-group "></div>
<button type="submit" value="submit" class="em-c-btn em-c-btn--primary">
<span class="em-c-btn__text">Submit</span>
</button>
</div>
</form>
<script type="text/javascript" src="../static/js/em-unity-1.6.0.min.js"></script>
</body>
Error I get
"Oracle client has already been initialized"
"'None Type' object has no attribute 'cursor'"
The first error suggests that you are calling cx_Oracle.init_oracle_client() more than one time. You aren't supposed to do that! See the documentation for details. You can perform the initialization directly in your module code, or you can use a global variable to ensure that it is only called once.
The second error suggests that you are trying to create a cursor on a None connection object -- which in turn suggests that your utils.CreateConnection() function is catching exceptions and returning None instead of a valid connection. Avoid catching exceptions unless you have to, and then ensure that you're not just swallowing the exception and causing exceptions elsewhere!
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.
I've been learning flask following this tutorial. Now I'm trying to test some parts of the application with python unittest. But I can't grasp how to test user login corrctly. Here's the code for the test I'm trying to do:
from intro_to_flask import app
from models import db
from models import User
class BaseTestCase(unittest.TestCase):
def setUp(self):
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://credentials/database'
app.config['TESTING'] = True
app.config['CSRF_ENABLED'] = False
with app.app_context():
db.create_all()
def tearDown(self):
with app.app_context():
db.session.remove()
db.drop_all()
def test_User_login(self):
tester = app.test_client(self)
u = User(firstname = 'testname', lastname = 'testlaname', email = 'test#example.com', password = 'pass')
with app.app_context():
db.session.add(u)
db.session.commit()
response = tester.post('/signin', data=dict(email = 'test#example.com', password = 'pass'), follow_redirects=True )
self.assertIn(b'Profile', response.data) #User is redirected to profile page after loggin in which has giant Profile
if __name__ == '__main__':
unittest.main()
The test fails and it's clear, that login and the following redirect doesn't happen.
I added the following print statements to the test:
print(response)
print(response.data)
Which produced the following results:
print(response)
<Response streamed [200 OK]>
print(response.data)
<!DOCTYPE html>
<html>
<head>
<title>Flask App</title>
<link rel="stylesheet" href="/static/css/main.css">
</head>
<body>
<header>
<div class="container">
<h1 class="logo">Image Hosting Test v 0.2</h1>
<nav>
<ul class="menu">
<li>Home</li>
<li>About</li>
<li>Contact</li>
<li>Sign Up</li>
<li>Sign In</li>
</ul>
</nav>
</div>
</header>
<div class="container">
<h2>Sign In</h2>
<form action="/signin" method=post>
<div style="display:none;"><input id="csrf_token" name="csrf_token" type="hidden" value="1463805648##fcc7e953937a80b6744554aed86d092fcf70e1fb"></div>
<label for="email">Email</label>
<input id="email" name="email" type="text" value="test#example.com">
<label for="password">Password</label>
<input id="password" name="password" type="password" value="">
<input id="submit" name="submit" type="submit" value="Sign In">
</form>
</div>
</body>
</html>
Can someone explain to me, what is wrong with my test?
Python version: 2.7.9
MySQL version: 5.7
Flask version: 0.10.1
OS Windows 10
Ah, I think it's CSRF protections that is causing it. Try to disable it with setting
app.config['WTF_CSRF_ENABLED'] = False
Index.html:
<html>
<head>
<title>Login Page</title>
<link type="text/css" rel="stylesheet" href="coach.css" />
</head>
<body>
<img src="images/logo-cel-transparent_0.png" width="74" height="64"><strong><img src="images/logo-cel-transparent_0.png" alt="Cel logo" width="74" height="64" align="right">
</strong>
<h1 align="center"><strong>Central Electronics Limited</strong></h1>
<p> </p>
<h2 align="center">Storage Management System</h2>
<p> </p>
<p align="center">Login To System</p>
<p align="center"> </p>
<form action="cgi-bin/validate.py" method="post">
<div align="center">Username :
<input type="text" name="username">
<br>
Password :
<input type="text" name="password">
<br>
<input type="submit" value="Submit">
</div>
</form>
<p align="center"> </p>
</body>
</html>
validate.py:
import cgi
import yate
import sqlite3
import sys
connection = sqlite3.connect('users.sqlite')
cursor = connection.cursor()
print('Content-type:text/html')
form=cgi.FieldStorage()
for each_form_item in form.keys():
if (each_form_item=='username'):
username=form[each_form_item].value
if (each_form_item=='password'):
password=form[each_form_item].value
result=cursor.execute('SELECT USERNAME from validate')
usernames=[row[0] for row in result.fetchall()]
print(usernames)
for each_username in usernames:
if (username==each_username):
pass_result=cursor.execute('SELECT PASSWORD from validate where username=?',(each_username,))
password1=[row[0] for row in pass_result.fetchall()]
for each_password in password1:
if (each_password==password):
with open("C:\Python34\ProjectShivam\webapp\cgi-bin\successvalidate.py") as f:
code = compile(f.read(), "successvalidate.py", 'exec')
exec(code)
else:
print('')
print('Login Failure')
successvalidate.py:
import yate
print(yate.start_response())
print(yate.para("Login Successful"))
print(yate.include_footer({"Click here to Go to Welcome Page":"/welcome.html"}))
simple_httpd.py(The server code):
from http.server import HTTPServer, CGIHTTPRequestHandler
port = 8080
httpd = HTTPServer(('', port), CGIHTTPRequestHandler)
print("Starting simple_httpd on port: " + str(httpd.server_port))
httpd.serve_forever()
I run the server(simple_httpd.py) using command prompt. The index page opens up. I enter the 1st set of username and password. It runs as expected and successvalidate.py opens up. But when i enter the 2nd set of username and password(i.e, the second row of table validate in users.sqlite)(validate table contains two set of usernames and passwords), it displays on cmd:
127.0.0.1 - - [18/Jun/2015 20:59:29] b'Traceback (most recent call last):\r\n F
ile "C:\\Python34\\ProjectShivam\\webapp\\cgi-bin\\validate.py", line 25, in <mo
dule>\r\n password1=[row[0] for row in pass_result.fetchall()]\r\nNameError:
name \'pass_result\' is not defined\r\n'
Also any other username does not result in the text 'Login Failure' being printed on the web browser but instead same error shows on server. What is wrong?
you are getting the error when this condition is not met:
if (username==each_username):
pass_result=cursor.execute('SELECT PASSWORD from validate where username=?',(each_username,))
set a default value to pass_result, e.g. pass_result = None and then handle it before using, e.g. if pass_result is not None:
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.