Python webbrowser not opening browser - python-2.7

I'm trying to familiarize myself with Python with a major concern for web publishing, so I looked around and found the following example. Running 2.7 in PyScripter on Windows 7 didn't bring up the browser as I expected. The code came up in Notepad++ instead, apparently since the html suffix was associated with Notepad. I tried about a dozen different permutations of the code, but the html file still opened in Notepad until I associated that file with Firefox. When I include the print webbrowser._browsers command, I get {'windows-default': [, None], 'c:\program files (x86)\internet explorer\iexplore.exe': [None, ]}
This would imply to me that IE should be the default browser being called, but obviously it is not. Can anyone enlighten me here as I am a Python newbie?
'''A simple program to create an html file froma given string,
and call the default web browser to display the file.'''
contents = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Hello</title>
</head>
<body>
Hello, World!
</body>
</html>
'''
import webbrowser
def main():
browseLocal(contents)
def strToFile(text, filename):
"""Write a file with the given name and the given text."""
output = open(filename,"w")
output.write(text)
output.close()
def browseLocal(webpageText, filename='C:\\Python27\\Programs\\tempBrowseLocal.html'):
'''Start your webbrowser on a local file containing the text
with given filename.'''
strToFile(webpageText, filename)
print webbrowser._browsers
webbrowser.open(filename)
main()

def browseLocal(webpageText):#take filename out of here
'''Start your webbrowser on a local file containing the text
with given filename.'''
#define filename here.
filename='C:\\Python27\\Programs\\tempBrowseLocal.html'
strToFile(webpageText, filename)
print webbrowser._browsers
webbrowser.open(filename)

Related

R Shiny and p5.js

I am using R Shiny to develop a web page and also include my own R code.
I am using p5.js(https://p5js.org/) to display a game in the web page.
As in the official web page says I have an HTML and the p5 javascript code together with the javascript library. If I run the HTML, that is, clicking right and pressing chrome to display I get the started example (https://p5js.org/get-started/) with no incidence.
Here it is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!--<meta name="viewport" content="width=device-width, initial-scale=1">-->
<script language="javascript" type="text/javascript" src="libraries/p5.js"> </script>
<script language="javascript" type="text/javascript" src="sketch.js"></script>
<!-- this line removes any default padding and style. you might only need one of these values set. -->
<style> body {padding: 0; margin: 0;} </style>
</head>
<body>
</body>
</html>
When I do the same in Shiny, running the code from R-Studio I do not get anything from it. I have stored the javascript files in the www folder as it is supposed to be and I currently know that my HTML called the javascript since I set an alert in the p5 javascript file, but outside the setup and draw methods. The problem is that, even though the alert is loaded, seems like the setup and draw methods are not called and, obviously, as a consequence, they do not load the canvas. I know that they are not called because I have a called to an alert in the setup method that works running the HTML file directly but not if I run the same file from R-Studio.
Here it is the p5 javascript code:
alert("GOOD1");
function setup() {
alert("GOOD2");
createCanvas(640, 480);
}
function draw() {
if (mouseIsPressed) {fill(0);}
else {fill(255);}
ellipse(mouseX, mouseY, 80, 80);
}
I load the HTML page in Shiny using the next line of code
... ,tabItem(tabName = "tabProcessing", htmlOutput("processingMasterThesis") ...
Attach to the tag "processingMasterThesis" I have the corresponding URL to the HTML file in the server.R, as it is supposed to be so the problem is not here.
Why may be the cause of this? It works if I call the HTML file directly to be load in the browser but not if I do it from R-Studio, why?
I have solved the problem. The p5 java script code will be:
// =====================
// "app/sketch.js"
// =====================
var myCanvas;
function setup() {
var idCanvas = 'divCanvas';
myCanvas = createCanvas(300, 300);
myCanvas.parent(idCanvas);
}
function draw() {
if (mouseIsPressed) {
fill(0);
} else {
fill(255);
}
ellipse(mouseX, mouseY, 80, 80);
}
The library you need to run the example can be found at https://p5js.org/
In this javascript file I have created an id that reference a html div element so that is the place where I will set my canvas. Once this is done, the rest of the javascript code will code perfectly. The point is to reference that the parent of the canvas is that div as you can see in the code.
After this you just have to create either in shiny or pure html code something like this:
# THE UI (File ui.R)
library(shiny)
library(shinydashboard)
library(rmarkdown)
shinyUI(
fluidRow(
# THE UI
tags$html(
tags$body(
singleton(tags$head(tags$script(src = "master_thesis/app/libraries/p5.js")))
,singleton(tags$head(tags$script(src = "master_thesis/app/sketch.js")))
,singleton(tags$div(id = 'divCanvas', style = 'width:auto; height:auto'))
))
)
)
The code that I show below is in shiny. The first "head" line include the library p5.js and the second "head" line just say "hey this is my p5 script file" and "divCanvas will be the div that I will print on".
You may have issues with the references to the javascript file. I think is worthy to note that you must create a www folder in your root shiny application. In this folder, you must put your javascript files. For example, as you can see in my code the two javascript files that I am using follow the next path:
ShinyApplication/www/app/libraries/p5.js
ShinyApplication/www/app/sketch.js
Hope this can help!

Incorrect displaying of russian characters in Python / Django

I am trying to parse a russian website using lxml. However ,I got an issue with displaying russian characters, that i am unable to overcome myself.
Let's take this html piece for example:
Квест в реальности «Карты, деньги, два стола»
I am using this piece to parse it:
title = root.xpath('//*[#id="event-id-41600"]/div[3]/div[2]/a/text()')[0].encode('utf-8').strip()
and this is what i get:
├É┬Ü├É┬▓├É┬Á├Ĺ┬ü├Ĺ┬é ├É┬▓ ├Ĺ┬Ç├É┬Á├É┬░├É┬╗├Ĺ┬î├É┬Ż├É┬ż├Ĺ┬ü├Ĺ┬é├É┬Ş ├é┬ź├É┬Ü├É┬░├Ĺ┬Ç├Ĺ┬é├Ĺ┬ő, ├É┬┤├É┬Á├É┬Ż├Ĺ┬î├É┬│├É┬Ş, ├É┬┤├É┬▓├É┬░ ├Ĺ┬ü├Ĺ┬é├É┬ż├É┬╗├É┬░├é┬╗
In database however instead of cyrillic i see this:
ÐвеÑÑ Ð² ÑеалÑноÑÑи «ÐаÑÑÑ, денÑги, два ÑÑола»
Oh and btw for reference:
this piece:
title = item.xpath('div[3]/div[2]/a')[0]
print etree.tostring(title)
returns me this :
Квест в реальности «Карты, деньги, два стола»
Not sure if it is database related of something to do with python encoding. Any help appreciated :)
Thanks in advance.
EDIT: i am using MySQL and Django ORM
Django settings:
DATABASE_OPTIONS = {
"charset": "utf8_general_ci",
"init_command": "SET storage_engine=INNODB"
}
Webpage :
<!DOCTYPE html>
<html lang="en" prefix="og: http://ogp.me/ns#" class="">
<head>
<title>Интересные события в Москве в январе - феврале 2016</title>
<meta charset="utf-8">
Cyrillic code page does not exist/not setted up on your server. So you can`t view russian characters in terminal even in UTF-8. But python stil work with unicode properly.
By this command:
title = root.xpath('//*[#id="event-id-41600"]/div[3]/div[2]/a/text()')[0].encode('utf-8').strip()
you get unicode string and encode it to bytes (str in python2). And save bytes in database.
When you load string from database python uses default code page (probably Latin-1) and you get this:
ÐвеÑÑ Ð² ÑеалÑноÑÑи «ÐаÑÑÑ, денÑги, два ÑÑола»
So, you should store unicode string in database (don't use encode)
title = root.xpath('//*[#id="event-id-41600"]/div[3]/div[2]/a/text()')[0].strip()
P.S. I don't understand how encode('Latin-1') helps (from comments), but problem is solved :)

Doing auto redirect using CherryPy

I've just discovered CherryPy. I am going through the tutorial, so far so good. While doing it I wanted to create a "BUSY DOING WORK" splash screen, essentially I have a python function that for example updates an sqlite table with 10000 records. What I want to do is get CherryPy to display a busy.html page while the database is being updated, when the database operation completes I want to redirect the user back to the main.html page.
So far I have only come across
dev update_db(self):
#Code to update the database goes here
return "busy.html"<----show user that work is being done
#database has completed
CherryPy.redirect "main.html"
But return simply exits the function. Is there anyway of doing presenting the user with a temporary splashscreen, while the database is being updated then returning the user back to another page once its complete.
I suppose an alternative is to have a message flash across the top of the existing page, But I don't know if CherryPy has a flash message feature much like Flask.
IMHO, you can achieve this with generators and here is a link from latest (v3.8) cherrypy documentation. However, you should take into account the following issue in the docs
Streaming generators are sexy, but they play havoc with HTTP. CherryPy allows you to stream output for specific situations: pages which take many minutes to produce, or pages which need a portion of their content immediately output to the client. Because of the issues outlined above, it is usually better to flatten (buffer) content rather than stream content. Do otherwise only when the benefits of streaming outweigh the risks.
Generators have some limitations as written in the documentation
you cannot manually modify the status or headers within your page handler if that handler method is a streaming generator, because the method will not be iterated over until after the headers have been written to the client. This includes raising exceptions like HTTPError, NotFound, InternalRedirect and HTTPRedirect. To use a streaming generator while modifying headers, you would have to return a generator that is separate from (or embedded in) your page handler.
Because the headers have already been written to the client when streaming, raising redirection exception cannot help to redirect to different page after your long running task. If I were you, I would yield this
<meta http-equiv="refresh" content="0;URL='/anotherpage'" />
or this at the final yield
<script>window.location.href="/anotherpage";</script>
I coded and example for you. I hope this gives you an idea.
# encoding: utf-8
import time
import cherrypy
class Root(object):
#cherrypy.expose
def index(self):
content = '''<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("body").append("<p>jQuery Ready</p>");
setTimeout(function(){
$("body").html("Redirecting Please Wait...")
}, 2500);
});
</script>
</head>
<body>
<p>Page Content1</p>
<p>Page Content2</p>
<p>Page Content3</p>
<p>Page Content4</p>
<p>Page Content5</p>
<p>Page Content Final</p>
</body>
</html>
'''
for line in content.split("\n"):
yield line
time.sleep(1)
else:
yield '''<meta http-equiv="refresh" content="5;URL='/anotherpage'" />'''
index._cp_config = {'response.stream': True}
#cherrypy.expose
def anotherpage(self):
return "Another Page"
cherrypy.quickstart(Root(), "/")

Listing and Linking contents of a folder in JSP doesn't work

I have to make a Web Application for downloading files from a folder.I use Tomcat as a server.I wrote a JSP page for listing the content of my data folder,and I tried to make links for each file from this folder.
The JSP page is this:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.io.File,java.io.IOException,java.util.*,java.io.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Contents <br>
<% File f = new File("C:\\Users\\name\\Desktop\\eclipse\\app\\PTW\\WebContent\\data\\"); // current directory
File[] files = f.listFiles();
for (File file : files) {
if (file.isDirectory()) {
//System.out.print("directory:");
} else {
%>
<a href="<%=file.getAbsolutePath()%>" target="_blank"><br> <%=file.getName() %>
</a>
<%
}
}
%>
</body>
</html>
The problem is that downloading these files is working only in I.E. and only if user selects Right CLick - Save target As.
So my way to do this is wrong!But I don't understand why?How to force downloading files from this JSP?
Thank You!
You must know that the path to the file on the file system is a different path than the URL. The file system is only known by your server, the URL is the path which is accessed by browsers.
Let's say your file is in /opt/tomcat/webapps/myApp/folder/file.jpg and you are running your Tomcat on www.example.com. If you generate (through JSP) a link like
Download File
Your browser will see this path as:
www.example.com/opt/tomcat/webapps/myApp/folder/file.jpg
Your browser will not find the file. The URL the browser would neet to find it is:
www.example.com/myApp/folder/file.jpg
Which consists of
the domain www.example.com
the servlet context myApp
the path inside the application to the file folder/file.jpg
So you need to build the path /myApp/folder/file.jpg in your JSP. You can do it this way:
Download
I use Expression Language here instead of scriptlets. This is considered better style as it improves maintaineance and readability.
Note: This will only work if your File is inside the webapplication directory (myApp). If it is outside, you will need a servlet to stream your files to the client, but that is an other story.

dompdf: templates & $_SESSION variables

i was wondering if this setup would work. i have to crank out a batch of PDF from a bunch of variables i'm pushing into the $_SESSION via a form (duh...). the idea is to pass the template file to the dompdf engine and have the template populate from the $_SESSION then out to PDF. it seems to me that when the $template gets loaded it should do that, yes?
here's the basic code:
<?php
function renderToPDF($theTemplate = "template.php") // this is just to show the value
{
require_once("dompdf/dompdf_config.inc.php");
$content = file_get_contents($theTemplate);
if ($content !== false)
{
$dompdf = new DOMPDF();
$dompdf->load_html($content);
$dompdf->render();
$dompdf->stream("kapow_ItWorks.pdf");
}
}
?>
and this is the template.php file (basically... you don't want all 16 pages...)
<html>
<meta>
<head>
<link href="thisPage.css" type="text/css" rel="stylesheet">
</head>
<body>
<h1><?php echo $_SESSION['someTitle'] ?></h1>
<h2>wouldn't it be nice, <?php echo $_SESSION['someName'] ?></h2>
</body>
</html>
so my thinking is that the template.php will pull the variables right out of the $_SESSION array without any intervention, looking like this:
BIG TITLE
wouldn't it be nice, HandsomeLulu?
i guess the nut of the question is: Do $_SESSION variables get evaluated when PHP files are loaded, but not rendered?
WR!
file_get_contents does not evaluate the PHP file, it simply gets its contents (the file as it is in the hard drive).
To do what you want, you need to use output buffering and include.
ob_start(); // Start Output beffering
include $theTemplate; // include the file and evaluate it : all the code outside of <?php ?> is like doing an `echo`
$content = ob_get_clean(); // retrieve what was outputted and close the OB
for some reason, the code ON the page that calls the function ALSO gets dumped into the file. this was placed before the header. i understand now why: i wasn't referencing an external page, i was importing and external page. don't know why that didn't click.
anyway. as soon as i got rid of the page's extra stuff, it worked just fine. in retrospect, what dompdf needed to state was quite simply that NO HTML of ANY kind (echo, print, &c.) can be on the page that calls the function. at least that what it appears to require at this level of my knowledge.
for those who, like me, are floundering in a misma of 'everything but the answer', here's the bare bones code that did the job:
buildPDF.php:
<?php
session_start();
$_SESSION['someTitle'] = "BIG FAT TITLE";
$_SESSION['someName'] = "HandomeLu";
$theTemplate = 'template.php';
function renderToPDF($templateFile)
{
require_once("_dox/dompdf/dompdf_config.inc.php");
ob_start();
include $templateFile;
$contents = ob_get_clean();
if ($contents !== false)
{
$dompdf = new DOMPDF();
$dompdf->load_html($contents);
$dompdf->render();
$dompdf->stream("kapow_ItWorks.pdf");
}
}
renderToPDF($theTemplate);
?>
and this is the template.php:
<!DOCTYPE HTML>
<html>
<meta>
<head>
<meta charset="utf-8">
<link href="thisPage.css" type="text/css" rel="stylesheet">
</head>
<body>
<h1><?php echo $_SESSION['someTitle'] ?></h1>
<p>wouldn't it be nice, <?php echo $_SESSION['someName'] ?></p>
</body>
</html>
also note that the external CSS file reads in just fine. so you can still keep the structure and style separate. also, the $_SESSION variables can be set anywhere, obviously, i just set them here to keep testing easy.
hope this is useful for those getting started with this GREAT class. if you're looking to get up and running cranking out PDF files, this kicks so much butt, it should have a trigger and a grip on it. :)
thanks to everyone who commented. you got me in the place i needed to be. :)
this site ROCKS.
WR!