Python localhost error on mac os sierra - python

I am using google maps which has a basic form for the user to fill in his details. On clicking submit the form details are suppose to get stored in the MySQL table that I have created.
I am using apache that is already pre-installed on my mac.
I have downloaded MySQL and its running fine. I have created the table with the required columns in it.
I am using PyCharm Community Edition for running my python scripts.
My map.html file (the one which has the google map with the form) is running fine on localhost.
However, on clicking submit I get the following error :
Not Found
The requested URL /Library/WebServer/CGI-Executables/processing.py was not found on this server.
My map.html file is in Library/WebServer/Documents/
#map.html file
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta charset="utf-8" />
<title>MAPS</title>
<style>
#map {
width: 100%;
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#description {
font-family: Calibri;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
display: none;
}
#map #infowindow-content {
display: none;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Calibri;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Calibri;
font-size: 16px;
font-weight: 400;
}
#pac-input {
background-color: #fff;
font-family: Calibri;
font-size: 15px;
font-weight: 400;
margin-left: 12px;
padding: 8px 12px;
text-overflow: ellipsis;
width: 400px;
border: 1px solid #ccc;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 400;
padding: 6px 12px;
}
#target {
width: 345px;
}
#form
{
display: none;
}
#heading {
text-align: center;
color: #003366;
font-size: 30px;
font-family: Calibri;
padding: 8px 12px;
}
label.field {
text-align: left;
font-weight: bolder;
font-size: 16px;
font-family: Calibri;
}
input[type=text], input[type=email], input[type=number], select {
font-family: Calibri;
font-size: 16px;
font-weight: bolder;
padding: 8px 12px;
width: 100%;
margin: 8px 0;
display: inline-block;
border: 1px solid black;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
font-family: Calibri;
font-size: 16px;
font-weight: bolder;
background-color: white;
color: #00b300;
padding: 8px 12px;
margin: 8px 0;
border: 2px solid #00b300;
border-radius: 4px;
cursor: pointer;
box-sizing: border-box;
}
input[type=submit]:hover {
background-color: #00b300;
color: white;
}
input[type=reset] {
font-family: Calibri;
font-size: 16px;
font-weight: bolder;
background-color: white;
color: #cc0000;
padding: 8px 12px;
margin: 8px 0;
border: 2px solid #cc0000;
border-radius: 4px;
cursor: pointer;
box-sizing: border-box;
}
input[type=reset]:hover {
background-color: #cc0000;
color: white;
}
input[type=text]:focus {
background-color: #f2f2f2;
border-color: #4d90fe;
}
input[type=email]:focus {
background-color: #f2f2f2;
border-color: #4d90fe;
}
input[type=number]:focus {
background-color: #f2f2f2;
border-color: #4d90fe;
}
select:focus {
background-color: #f2f2f2;
border-color: #4d90fe;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC8EAfEQrYVs4c_kMBUQw3tVY8uhEViDCU&libraries=places&callback=initAutocomplete"
async defer>
</script>
</head>
<body>
<div id="map"></div>
<input id="pac-input" class="controls" type="text" placeholder="Search your location..." />
<div id="form">
<form action="Library/WebServer/CGI-Executables/processing.py" method="post">
<p id="heading">PERSONAL INFORMATION</p>
<label class="field" for="fullname"><b>Full Name:</b></label>
<input type="text" name="fullname" placeholder="Eg. Suraj Makhija" size="30" required />
<br />
<br />
<label class="field" for="emailid"><b>E-mail:</b></label>
<input type="email" name="emailid" placeholder="Eg. contact#domain.com" size="30" required />
<br />
<br />
<label class="field" for="mobile"><b>Mobile:</b></label>
<input type="text" name="mobile" placeholder="Eg. 9999999999" maxlength="10" minlength="10" size="30" required />
<br />
<br />
<label class="field" for="gender"><b>Gender:</b></label>
<select name="gender" required>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
<br />
<br />
<label class="field" for="areaofexpertise"><b>Area of Expertise:</b></label>
<input type="text" name="areaofexpertise" placeholder="Eg. Android/iOS Developer" size="30" required />
<br />
<br />
<label class="field" for="yearsofexperience"><b>Years of Experience:</b></label>
<input type="number" name="yearsofexperience" placeholder="Eg. 10" min="0" max="100" required />
<br />
<br />
<p style="text-align: center;">
<input type="submit" value="Submit" />
<input type="reset" value="Clear All" />
</p>
</form>
</div>
<script>
var map;
var iconBase;
var input;
var searchBox;
var markers=[];
var markerArray =[];
var infowindow;
function initAutocomplete() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 20.5937, lng: 78.9629},
zoom: 5,
mapTypeId: 'roadmap',
gestureHandling: 'cooperative'
});
//Declaring infowindow.
infowindow = new google.maps.InfoWindow({
content: document.getElementById('form')
});
// Create the search box and link it to the UI element.
input = document.getElementById('pac-input');
searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
//Creates a marker when the user clicks on a location on the map.
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng, map);
});
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
//Marker function declaration.
function addMarker(location, map) {
// Add the marker at the clicked location.
var iconBase = 'https://maps.google.com/mapfiles/kml/paddle/';
marker = new google.maps.Marker({
draggable: true,
animation: google.maps.Animation.DROP,
position: location,
map: map,
icon: iconBase + 'ylw-blank.png'
});
//Infowindow pops up on clicking the marker.
google.maps.event.addListener(marker, 'click', function() {
document.getElementById('form').style.display='inline-block';
infowindow.open(map, marker);
});
}
</script>
</body>
</html>
My processing.py file (the python script that is used for processing the form data and inserting into the MySQL table) is in Library/WebServer/CGI-Executables/
I haven't made any changes to my httpd.conf file except for adding .py to AddHandler statement.
I am attaching all my files below.
Please help me with this as I have been stuck on this for a very long time now.
Please note that Im using Mac OS Sierra.
Thanks in advance.
#processing.py file
import MySQLdb
import cgi
import cgitb
cgitb.enable()
form = cgi.FieldStorage()
fullname = form.getvalue('fullname', '')
emailid = form.getvalue('emailid', '')
mobile = form.getvalue('mobile', '')
gender = form.getvalue('gender', '')
areaofexpertise = form.getvalue('areaofexpertise', '')
yearsofexperience = form.getvalue('yearsofexperience', '')
db = MySQLdb.connect(host="localhost", user="root", passwd="*****", db="client_database")
cursor = db.cursor()
query = """INSERT INTO client_info (FULL_NAME, EMAIL_ID, MOBILE, GENDER, AREA_OF_EXPERTISE, YEARS_OF_EXPERIENCE)
VALUES (%s, %s, %s, %s, %s, %s)"""
cursor.execute(query, (fullname, emailid, mobile, gender, areaofexpertise, yearsofexperience))
result = cursor.fetchall()
db.commit()
db.close()

Related

index.html working well, localhost:5000/ not showing background

index.html working well, localhost:5000/ not showing background, help!
i set the correct path to style.css and it works opened using index. But i do using server localhost:5000/ and it doesn't show any background. not sure what im doing wrong.
when i try to inspect from browser it say ERROR 404, style.css NOT FOUND
i just want to show the background animated like it seems in codepen.
Here is my code app.py:
# -------------------- Importaciones -------------------- #
from flask import Flask, render_template, request, redirect
from flask import send_from_directory
# -------------------- App -------------------- #
app = Flask(__name__) # Creo la app.
# -------------------- ROUTES -------------------- #
#app.route('/') # Página principal, qué se llama index.
def start(): # Creo una función que me retorne con un return hacia la página.
return render_template('website/index.html')
#app.route('/register') # Página de registro.
def register():
return render_template('website/register.html')
#app.route('/loged') # Página para logearse.
def loged():
return render_template('website/loged.html')
#app.route('/us') # Página de nosotros.
def us():
return render_template('website/us.html')
if __name__ == '__main__': # Inicializamos nuestra app con el .run.
app.run(debug = True)
-------------------------------
index.html code:
<!-- Importaciones y demás -->
<!DOCTYPE html>
<html lang="es">
<head>
<title>Título</title>
<link rel="stylesheet" href="css/style.css" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
</head>
<!-- Comienza el código -->
<body>
<header>
<div class="main">
<!-- Menú cabecera -->
<nav class="navbar navbar-expand navbar-light bg-light">
<div class="nav navbar-nav">
<a class="nav-item nav-link" href="/register" aria-current="page">Registrarse</a>
<a class="nav-item nav-link" href="/loged">Iniciar sesión</a>
<a class="nav-item nav-link" href="#">FREE</a>
<a class="nav-item nav-link" href="/us">Nosotros</a>
</div>
</nav>
<!-- Boton de Iniciar sesión -->
<!--<button class="pulse" onclick="window.location.href='http://Tibia.com';" >
<b>Iniciar sesion</b>
</button>-->
<!-- Animación fondo -->
<div class="d1"></div>
<div class="d2"></div>
<div class="d3"></div>
<div class="d4"></div>
</div>
</header>
</body>
</html>
style.css code:
*{
margin: 0;
padding: 0;
background-color: #ffffff;
}
.main {
height: 100vh;
width: 100vw;
position: relative;
}
.d1 {
position: absolute;
background-image: url(../image/Leesinbackground.png);
background-size: 1920px 1080px;
height: 30vh;
width: 15vw;
background-position: 0 50%;
box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.8);
top: 50%;
transform: translateY(-50%);
z-index: 2;
animation: dd1 10s 1, dd12 10s 1;
animation-delay: 4s, 14s;
}
.d2 {
position: absolute;
background-image: url(https://images4.alphacoders.com/817/817016.png);
background-size: 1920px 1080px;
height: 50vh;
width: 25vw;
background-position: -10vw 50%;
left: 10vw;
box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.8);
top: 50%;
transform: translateY(-50%);
z-index: 1;
animation: dd2 10s 2;
animation-delay: 4s;
}
.d3 {
position: absolute;
background-image: url(https://images4.alphacoders.com/817/817016.png);
background-size: 1920px 1080px;
overflow: hidden;
height: 100vh;
width: 40vw;
left: 25vw;
box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.8);
background-position: -35vw 50%;
top: 50%;
transform: translateY(-50%);
z-index: 3;
animation: dd3 10s 2;
animation-delay: 4s;
}
.d4 {
position: absolute;
overflow: hidden;
background-image: url(https://images4.alphacoders.com/817/817016.png);
background-size: 1920px 1080px;
height: 80vh;
width: 25vw;
left: 60vw;
background-position: -70vw 50%;
top: 50%;
transform: translateY(-50%);
z-index: 1;
animation: dd4 10s 2;
animation-delay: 4s;
}
#keyframes dd1 {
0% {
}
50% {
width: 95vw;
}
}
#keyframes dd12 {
0% {
}
50% {
background-position: Calc(0vw - 40px) 50%;
}
}
#keyframes dd2 {
0% {
}
50% {
background-position: Calc(-10vw - 40px) 50%;
}
}
#keyframes dd3 {
0% {
}
50% {
background-position: Calc(-35vw - 40px) 50%;
}
}
#keyframes dd4 {
0% {
}
50% {
background-position: Calc(-70vw - 40px) 50%;
}
}
/*------------------------- Boton -------------------------*/
.pulse:hover,
.pulse:focus {
-webkit-animation: pulse 1s;
animation: pulse 1s;
box-shadow: 0 0 0 2em transparent;
}
#-webkit-keyframes pulse {
0% {
box-shadow: 0 0 0 0 var(--hover);
}
}
#keyframes pulse {
0% {
box-shadow: 0 0 0 0 var(--hover);
}
}
.pulse {
--color: #4f0909;
--hover: #1b06a7;
}
button {
color: var(--color);
transition: 0.25s;
}
button:hover, button:focus {
border-color: var(--hover);
color: rgb(18, 0, 108);
}
body {
font: 300 1em "Fira Sans", sans-serif;
}
button {
background: none;
border: 2px solid;
font: inherit;
line-height: 1;
margin: 0.5em;
padding: 1em 2em;
}
h1 {
font-weight: 400;
}
code {
color: #e4cb58;
font: inherit;
}
/*------------------------- OTROS -------------------------*/

wtf form change style on file input

I am using wtf forms with flask to create a form.
I have a file input, which is styled so the default button is not shown.
How can I dynamically change the style after a file is loaded?
Here is my code:
html:
<div class="file-upload my-form">
<img src="https://i.stack.imgur.com/dy62M.png" />
{{ wtf.form_field(form.file)}}
</div>
css:
.my-form input {
margin: 0;
padding: 0;
height: 100%;
opacity: 0;
}
.file-upload {
margin: 40px auto;
border: 1px solid #149174;
border-radius: 100px;
overflow: hidden;
position: relative;
}
.file-upload input {
position: absolute;
width: 300px;
height: 600px;
left: 10px;
top: 20px;
}
.file-upload img {
height: 170px;
width: 170px;
margin: 60px;
}
how can I change the style on input? or show a label with the file name in the worst case...
In the end I dealt with it like this:
function fileCheck() {
var checked = document.getElementById('file')
if (checked.value.length > 0) {
var file_name = checked.value.split(/(\\|\/)/g).pop();
var re = /(?:\.([^.]+))?$/;
var ext = re.exec(file_name)[1];
if (ext != 'pdf') {
document.getElementById('file-container').style.backgroundColor = '#ca2c2c';
document.getElementById("file-desc").innerHTML = "File Loaded with illegal extension: " + ext + " !!";
document.getElementById("final-submit").disabled = true;
}
else {
document.getElementById('file-container').style.backgroundColor = '#149174';
document.getElementById("file-desc").innerHTML = "File Loaded: " + checked.value.split(/(\\|\/)/g).pop();
document.getElementById("final-submit").disabled = false;
}
}
else {
document.getElementById("final-submit").disabled = true;
}
}
And my html looks like this:
<div class="file-upload my-form" id="file-container">
<img src="static/images/upload_icon.png" />
{{ form.file(oninput="fileCheck()") }}
</div>

How to pass parameter variable from Django web to python script?

I have a python script that will be triggered to read an inbox and send email to an gmail account when some condition is meet. In order to send , the script will filter through subject or text of the incoming email. Currently the script is just hard-coded format and I prefer the condition is dynamically set by the user. I created a django website and let user to input their condition, but I do not know how can I pass the parameter from the web to my python script. I already do my researched on the internet but couldn't found any useful source, does anyone can help me or send my any related article for me to read ? Thanks
My py script
import datetime
import email
import imaplib
import mailbox
import smtplib
EMAIL_ACCOUNT = "xxx#gmail.com"
PASSWORD = "xxx"
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(EMAIL_ACCOUNT, PASSWORD)
mail.list()
mail.select('inbox')
result, data = mail.uid('search', None, "UNSEEN") # (ALL/UNSEEN)
i = len(data[0].split())
for x in range(i):
latest_email_uid = data[0].split()[x]
result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
# result, email_data = conn.store(num,'-FLAGS','\\Seen')
# this might work to set flag to seen, if it doesn't already
raw_email = email_data[0][1]
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
# Header Details
date_tuple = email.utils.parsedate_tz(email_message['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
local_message_date = "%s" %(str(local_date.strftime("%a, %d %b %Y %H:%M:%S")))
email_from = str(email.header.make_header(email.header.decode_header(email_message['From'])))
email_to = str(email.header.make_header(email.header.decode_header(email_message['To'])))
subject = str(email.header.make_header(email.header.decode_header(email_message['Subject'])))
# Body details
for part in email_message.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True)
print("From:", email_from)
print("Email To:", email_to)
print("date:", local_message_date)
print("Subject:", subject)
print("body:", body.decode('utf-8'))
'''If subject have test it will send specific email to recipient'''
if "Consent" in subject:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(EMAIL_ACCOUNT, PASSWORD)
msg = "ALERT NOTICE!"
server.sendmail(EMAIL_ACCOUNT, "xxx#gmail.com", msg)
server.quit()
else:
print( "no email");
else:
continue
My django web currently is just html form
My django web interface
Html
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Quicksand:300,500" rel="stylesheet">
<style>
body {font-family: 'Quicksand', sans-serif;}
.button {
border-radius: 50px;
background-color: #ff9633;
border: none;
color: #FFFFFF;
text-align: center;
font-size: 15px;
padding: 10px;
width: 80px;
transition: all 0.5s;
cursor: pointer;
margin: 5px;
margin-left:500px;
}
.button span {
cursor: pointer;
display: inline-block;
position: relative;
transition: 0.5s;
}
.button span:after {
content: '\00bb';
position: absolute;
opacity: 0;
top: 0;
right: -20px;
transition: 0.5s;
}
.button:hover span {
padding-right: 25px;
}
.button:hover span:after {
opacity: 1;
right: 0;
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 45%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
}
/* Add Animation */
#-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
#keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
/* The Close Button */
.close {
color: white;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.modal-header {
padding: 2px 16px;
background-color: #ff9633;
color: white;
}
.modal-body {padding: 2px 16px;}
.modal-footer {
padding: 2px 16px;
background-color: #ff9633;
color: white;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #ff9633;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover {
background-color:
#fa7d34;
}
</style>
</head>
<body>
<ul>
<li><div id="myBtn1">Alert Policies</div></li>
<li>Test3</li>
<li>Test4</li>
</ul>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Alert Policies</h2>
</div>
<div class="modal-body">
<p style="font-size:14px">Please select an event parameter as well as the condition type and value that apply.</p>
<!-- parameter drop down -->
<form action="/action_page.php">
<label for="Parameter"> <b style="font-size:13px" > Event parameter to evaluate </b></label>
<select name="Parameter" id="Parameter" style="width:340px; font-family: 'Quicksand', sans-serif;">
<option disabled selected value>select a parameter</option>
<option value="Subject">Subject</option>
<option value="Text">Text</option>
</select>
<br><br>
<label for="Condition"> <b style="font-size:13px" > Type of condition </b></label>
<select name="Condition" id="Condition" style="width:340px; margin-left:69px; font-family: 'Quicksand', sans-serif;">
<option disabled selected value>select a condition</option>
<option value="Equals">Equals</option>
<option value="Contain">Contain</option>
<option value="NotContain">Does not contain</option>
</select>
<br><br>
<label for="valuetomatch"> <b style="font-size:13px" > Value to match</b></label>
<input type="text" id="valuetomatch" name="valuetomatch" style="width:333px; margin-left:80px; font-family: 'Quicksand', sans-serif;">
<br>
<br>
<button class="button"><span>OK</span></button>
</form>
</div>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn1");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
If your condition data is serializable, then you can use Celery to run python script. It'll be as simple as:
# in your Django code that run on user submitting data
...
send_email.delay()
...
# Celery task
#shared_task(bind=True)
def send_email(list_of_your_condition_parameters):
# do job

How to render a 3D object to HTML file by using pythonOCC in Django?

I have a Django application and I'm using pythonOCC package in it. I have to display the 3D .stl, .stp, .igs files in my template. Normally, when I call the render() function, the following outputs appear on my vscode console and since flask app created by pythonocc instead of django starts running in localhost, my index.html is never rendered. However I need to display the files in a Django template. That's why I have extended the X3DomRenderer Class such as below.
My custom X3DomRenderer class:
class CustomX3DomRenderer(x3dom_renderer.X3DomRenderer):
def render_to_string(self):
self.generate_html_file(self._axes_plane, self._axes_plane_zoom_factor)
return open(self._html_filename, 'r').read()
the HTML codes that returned from render_to_string() function:
<html lang="en">
<head>
<title>pythonOCC 7.4.0 x3dom renderer</title>
<meta name='Author' content='Thomas Paviot - tpaviot#gmail.com'>
<meta name='Keywords' content='WebGl,pythonOCC'>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="https://x3dom.org/release/x3dom.css">
<script src="https://x3dom.org/release/x3dom.js"></script>
<style>
body {
background: linear-gradient(#ced7de, #808080);
margin: 0px;
overflow: hidden;
}
#pythonocc_rocks {
padding: 5px;
position: absolute;
left: 1%;
bottom: 2%;
height: 38px;
width: 280px;
border-radius: 5px;
border: 2px solid #f7941e;
opacity: 0.7;
font-family: Arial;
background-color: #414042;
color: #ffffff;
font-size: 14px;
opacity: 0.5;
}
#commands {
padding: 5px;
position: absolute;
right: 1%;
top: 2%;
height: 65px;
width: 180px;
border-radius: 5px;
border: 2px solid #f7941e;
opacity: 0.7;
font-family: Arial;
background-color: #414042;
color: #ffffff;
font-size: 14px;
opacity: 0.5;
}
a {
color: #f7941e;
text-decoration: none;
}
a:hover {
color: #ffffff;
}
</style>
</head>
<body>
<x3d id="pythonocc-x3d-scene" style="width:100%;border: none" >
<Scene>
<transform scale="1,1,1">
<transform id="plane_smallaxe_Id" rotation="1 0 0 -1.57079632679">
<inline url="https://rawcdn.githack.com/x3dom/component-editor/master/static/x3d/plane.x3d" mapDEFToID="true" namespaceName="plane"></inline>
<inline url="https://rawcdn.githack.com/x3dom/component-editor/master/static/x3d/axesSmall.x3d" mapDEFToID="true" namespaceName="axesSmall"></inline>
</transform>
<inline url="https://rawcdn.githack.com/x3dom/component-editor/master/static/x3d/axes.x3d" mapDEFToID="true" namespaceName="axes"></inline>
</transform>
<transform id="glbal_scene_rotation_Id" rotation="1 0 0 -1.57079632679"> <Inline onload="fitCamera()" mapDEFToID="true" url="shp6b8ef6d6e61744489de16a6798cfe998.x3d"></Inline>
</transform> </Scene>
</x3d>
<div id="pythonocc_rocks">
pythonocc-7.4.0 x3dom renderer
<br>Check our blog at
<a href=http://www.pythonocc.org>http://www.pythonocc.org</a>
</div>
<div id="commands">
<b>t</b> view/hide shape<br>
<b>r</b> reset view<br>
<b>a</b> show all<br>
<b>u</b> upright<br>
</div>
<script>
var selected_target_color = null;
var current_selected_shape = null;
var current_mat = null;
function fitCamera()
{
var x3dElem = document.getElementById('pythonocc-x3d-scene');
x3dElem.runtime.fitAll();
}
function select(the_shape) // called whenever a shape is clicked
{
// restore color for previous selected shape
if (current_mat) {
current_mat.diffuseColor = selected_target_color;
}
// store the shape for future process
current_selected_shape = the_shape;
console.log(the_shape);
// store color, to be restored later
appear = current_selected_shape.getElementsByTagName("Appearance")[0];
mat = appear.getElementsByTagName("Material")[0];
current_mat = mat;
console.log(mat);
selected_target_color = mat.diffuseColor;
mat.diffuseColor = "1, 0.65, 0";
//console.log(the_shape.getElementsByTagName("Appearance"));//.getAttribute('diffuseColor'));
}
function onDocumentKeyPress(event) {
event.preventDefault();
if (event.key=="t") { // t key
if (current_selected_shape) {
if (current_selected_shape.render == "true") {
current_selected_shape.render = "false";
}
else {
current_selected_shape.render = "true";
}
}
}
}
// add events
document.addEventListener('keypress', onDocumentKeyPress, false);
</script>
</body>
</html>
and here is my view:
def occ_viewer(request):
shape = read_step_file(os.path.join('C:/Users/imgea/desktop/bgtask/bgtask/ThreeDFile', 'splinecage.stp'))
my_renderer = extend_x3dom.CustomX3DomRenderer(path='C:/Users/imgea/desktop/bgtask/bgtask/ThreeDFile')
my_renderer.DisplayShape(shape)
context = {'viewer': my_renderer.render_to_string()}
return render(request, 'success.html', context)
and I have added these HTML codes that I got from render_to_string() function to my template file. The viewer's grid has shown but the 3D object hasn't because of the error below.
Page not found: http://127.0.0.1:8000/file/occview/shp6b8ef6d6e61744489de16a6798cfe998.x3d
The library creates that .x3d file in the same directory with the file that I wanna render to template but I guess the viewer is looking for this .x3d file in the error which I mentioned before even I sent the directory. I couldn't find the cause of this error. Am I missing something?
Thank you!!

API question - How to REST request with Python

I'm making an API REST request using Python. And I encountered the following html result that says "Service - Endpoint not found. Please see the service help page for constructing valid requests to the service"
How can I fix this issue?
Note: This API can help determine whether an individual address is up to date by inputting individual address, first name, last name, etc.
Python query
import requests
import json
url = 'https://smartmover.melissadata.net/v3/WEB/SmartMover/doSmartMover/'
payload = {'t': '1353', 'id': 'sw38hs47u', 'jobid': '1', 'act': 'NCOA, CCOA', 'cols': 'TransmissionResults,TransmissionReference, Version, TotalRecords,CASSReportLink,NCOAReportLink,Records,AddressExtras,AddressKey,AddressLine1,AddressLine2,AddressTypeCode,BaseMelissaAddressKey,CarrierRoute,City,CityAbbreviation,CompanyName,CountryCode,CountryName,DeliveryIndicator,DeliveryPointCheckDigit,DeliveryPointCode,MelissaAddressKey,MoveEffectiveDate,MoveTypeCode,PostalCode,RecordID,Results,State,StateName,Urbanization', 'opt': 'ProcessingType: Standard', 'List': 'test', 'full': 'PATEL MANISH', 'first':'MANISH','last':'PATEL', 'a1':'1600 S 5TH ST', 'a2':'1600 S 5TH ST', 'city':'Austin', 'state': 'TX', 'postal': '78704', 'ctry': 'USA'}
response = requests.get(url, params=payload)
print (response.text)
Result
<?xml version="1.0" encoding="utf-8"?>
<!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">
<head>
<title>Service</title>
<style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style>
</head>
<body>
<div id="content">
<p class="heading1">Service</p>
<p xmlns="">Endpoint not found. Please see the <a rel="help-page" href="https://smartmover.melissadata.net/v3/WEB/SmartMover/help">service help page</a> for constructing valid requests to the service.</p>
</div>
</body>
</html>
[Finished in 0.9s]
Remove the / at the end of the url:
import requests
import json
url = 'https://smartmover.melissadata.net/v3/WEB/SmartMover/doSmartMover' # <<<
payload = {'t': '1353', 'id': 'sw38hs47u', 'jobid': '1', ...}
response = requests.get(
url, params=payload,
headers={'Content-Type': 'application/json'} # Using JSON here for readability in the response
)
print (response.text)
Output:
{
"CASSReportLink": "",
"NCOAReportLink": "",
"Records": [],
"TotalRecords": "",
"TransmissionReference": "1353",
"TransmissionResults": "SE20",
"Version": "4.0.4.48"
}

Categories