How to read text from a raw Dropbox text file in CircuitPython? - python-requests

I am trying to read a text file from Dropbox on a Raspberry Pi Pico with CircuitPython using adafruit_requests.
The file should be available to view and download "for everybody who has the link". When I enter the url with ?raw=1, it leads to a website containing only the string of text.
I connected via Wifi and ran
from adafruit_requests import get
response = get("https://www.dropbox.com/s/<content_ID>/file_name.txt?raw=1")
content = response.text
Now, when I ran
print(content)
I got the following output:
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Dropbox</title>
<link href="https://cfl.dropboxstatic.com/static/metaserver/static/css/error.css" rel="stylesheet" type="text/css"/>
<link rel="shortcut icon" href="https://cfl.dropboxstatic.com/static/metaserver/static/images/favicon.ico"/>
</head>
<body>
<div class="figure">
<img src="https://cfl.dropboxstatic.com/static/metaserver/static/images/illustration_catalog/sickbox-illo_m1.png" srcset="https://cfl.dropboxstatic.com/static/metaserver/static/images/illustration_catalog/sickbox-illo_m1#2x.png 2x" alt="Error: 5xx"/>
</div>
<div id="errorbox">
<h1>Error</h1>Something went wrong. Don't worry, your files are still safe and the Dropboxers have been notified. Check out our Help Center and forums for help, or head back to home.
</div>
<script>
function read_cookie (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
}
function localize() {
var locale = read_cookie('locale');
if (locale) {
var msg = message[locale];
if (msg) {
var elem = document.getElementById('errorbox');
if (elem) {
elem.innerHTML = msg;
}
}
}
}
localize();
</script>
</body>
</html>
Obviously, this is not the .txt file I uploaded to Dropbox, but an error message.
Is there a way to read the raw text file from Dropbox into a variable of type string in CircuitPython?
Note: When I use my Laptop and regular Python 3, I can easily obtain the string I want by executing
import requests
response = requests.get("https://www.dropbox.com/s/<content_ID>/file_name.txt?raw=1")
content = response.content
(Here, I am using response.content which, in the CircuitPython example produces the same error message as response.text but encoded differently. The two modules are not identical in their output.)

Related

Adding javascript dynamically using ExecuteJavaScriptAsync() API in OnContextCreated event remove elements in HTML HEAD tag ( wpf cefsharp 83.4.20.0)

I have a web page making ActiveX calls. Currently the page is loaded in IE embedded browser. Now I am planning to start using CEF as embedded web browser. I want to achieve this without modifying the existing code.
My Sample web page code:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Test ActiveXObject</title>
</head>
<body onload="myFunction()">
<script type="text/javascript" >
function CallSampleApi()
{
var obj = new ActiveXObject("Global.Pref");
var prefs = obj.Create("Pref.myPref");
if (prefs != null ) {
return prefs.SampleAPI();
}
else {
return 'not caught';
}
}
function myFunction() {
var message = "<h1 align='center'>Browser is Chrome </h1>" +
"<table border='1' width=500>" +
"<tr bgcolor='grey'><th width=300>Function Name</th><th width=200>Result</th></tr>" +
"<tr><td>Call Sample Api</td><td align='center'>" + CallSampleApi() + "</td></tr>" +
"</table>" ;
document.write(message);
}
</script>
</body>
</html>
I am using WPF cefsharp library for embedded web browser. In my WPF code, i have written a wrapper for this ActiveXObject and adding javascript dynamically using ExecuteJavaScriptAsync() API in OnContextCreated event. This works fine. But the problem is, this code somehow removes all tag in my html file which is strange.
public void OnContextCreated(IWebBrowser browserControl, IBrowser browser, IFrame frame)
{
if (_script != null && frame.IsMain)
{
if (frame.Url.Contains("dev")) // avoid dev tools call
string script = #"class ActiveXObject {
constructor(name) {
}
Create(nativeObj) {
switch (nativeObj) {
case 'Pref.myPref':
return new Preferences();
default:
return null;
}
}
}
class Preferences {
constructor() {
}
SampleAPI() {
return 'I am caught';
}
}";
frame.ExecuteJavaScriptAsync(script);
}
}
Source of the page loaded in cef embedded browser:
<html>
<head></head>
<body>
<h1 align="center">Browser is Chrome </h1>
<table border="1" width="500"><tbody><tr bgcolor="grey"><th width="300">Function Name</th><th width="200">Result</th></tr><tr><td>Call Sample Api</td><td align="center">I am caught</td></tr></tbody></table>
</body>
</html>
Not sure how HEAD elements are removed. If i remove onload event from html page and move the content within SCRIPT tag, it works fine.

is there a a way to parse a string and use querySelector with corvid wix?

I fetched a html page as a string and would like to retrieve the text between tags and get a value from a json key.
In javascript, this works :
For instance, if the string is :
<!doctype html>
<html lang="fr-FR">
<head>
<script>
window.changeTargetingData = {
"petition":{
"id":"19197290",
"signatureCount":{"total":323030,"displayed":323030}
}
};
</script>
</head>
</html>
This gives me what I want in javascript :
const doc = new DOMParser().parseFromString(textResponse, 'text/html');
const script = doc.querySelector('script');
const objJSON = script.textContent.match(/window.changeTargetingData = ([^]+);/)[1];
const obj = JSON.parse(objJSON);
console.log(obj.petition.signatureCount.total);
but I didn't find DOMParser or any DOM requests in corvid. Does anything exists to get a value from a html page ?
Thanks.
OK, you just need to change what is written on the doc.
It's :
import { JSDOM } from 'jsdom';
const domm = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
console.log(domm.window.document.querySelector("p").textContent);
and now it works....

CSS Issue with Node.JS / EJS

I know similar questions have been asked before, but I've had a good look through & unfortunately none of the answers are helping me.
My CSS file is being ignored in certain circumstances.
So in my app.js file I have this code, defining my view engine setup
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
In my index.js file I have the following the code for UserList page
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db; // (1) Extract the db object we passed to our HTTP request
var collection = db.get('usercollection'); // (2) Tell our app which collection we want to use
// (3) Find (query) results are returned to the docs variable
collection.find({},{},function(e,docs){
res.render('userlist', { "userlist" : docs }); // (4) Render userlist by passing returend results to said variable
});
});
Finally, my userlist.ejs page looks like this:
<!DOCTYPE html>
<html>
<head>
<title>User List</title>
<link rel='stylesheet' href='/stylesheets/style.css' type="text/css" />
</head>
<body>
<h1>User List</h1>
<ul>
<%
var list = '';
for (i = 0; i < userlist.length; i++) {
list += '<li>' + userlist[i].username + '</li>';
}
return list;
%>
</ul>
</body>
</html>
But when I run my page the CSS file is not loaded. However if I exclude this code:
<%
var list = '';
for (i = 0; i < userlist.length; i++) {
list += '<li>' + userlist[i].username + '</li>';
}
return list;
%>
The CSS file is loaded and applied without issue. Can anyone tell me why this is please? Apologies for the newbie question, but I've been trying to figure this out for ages.
I should mention the 'h1' tags are ignored too. The only thing rendered is the list items.
Not sure if its relevant, but my app is connecting to MongoDB to return the user data.
Any assistance would be very much appreciated!
Thank you!
Make sure that your CSS file is either defined as an endpoint in your index.js file or make sure that public/stylesheets/style.css exists so it can be loaded through the app.use(express.static(path.join(__dirname, 'public'))); command.

What needs to be changed in this code to make the page on top of it that loads this in a iframe change load a new url?

ok so heres my code
<html>
<head>
<title></title>
<body>
<script>
<!--
/*
Cookie Redirect. Written by PerlScriptsJavaScripts.com
Copyright http://www.perlscriptsjavascripts.com
Free and commercial Perl and JavaScripts
*/
// page to go to if cookie exists
go_to = "http://www.cookieisthere.com";
// number of days cookie lives for
num_days = 365;
function ged(noDays){
var today = new Date();
var expr = new Date(today.getTime() + noDays*24*60*60*1000);
return expr.toGMTString();
}
function readCookie(cookieName){
var start = document.cookie.indexOf(cookieName);
if (start == -1){
} else {
window.location = go_to;
}
}
readCookie("seenit");
// -->
</script>
</body>
</html>
This page will load on a page through a iframe... if the cookie is their i want the parent window to go to http://www.cookieisthere.com not the original page. After reading up on it a bit some people say use _top where the link is but i dont know how to do this. All help is much appreciated :)
Try this instead
<html>
<head>
<title></title>
<body>
<script>
<!--
/*
Cookie Redirect. Written by PerlScriptsJavaScripts.com
Copyright http://www.perlscriptsjavascripts.com
Free and commercial Perl and JavaScripts
*/
// page to go to if cookie exists
go_to = "http://www.cookieisthere.com";
// number of days cookie lives for
num_days = 365;
function ged(noDays){
var today = new Date();
var expr = new Date(today.getTime() + noDays*24*60*60*1000);
return expr.toGMTString();
}
function readCookie(cookieName){
var start = document.cookie.indexOf(cookieName);
if (start == -1){
} else {
window.top.location = go_to;
}
}
readCookie("seenit");
// -->
</script>
</body>
</html>

Pop up window not appending text

I am trying to implement a 'Trace Window' pop up window when I enter a website, and then send messages to that window throughout the website in Order to diagnose some of the more awkward issues i have with the site.
The Problem is that the page changes, if The trace window already exists, all content is removed, before the new TraceText is added.
What I want is a Window that can be sent messages from any page inside the website.
I have a javascript Script debugger.js which I include as a script in every screen (shown below) I would then call the sendToTraceWindow() function to send a message to it thoughout the website. this is currently Mostly done in vbscript at present, due to the issues i am currenctly investigating.
I think it is because i am scripting in the debugger.js into every screen, which sets the traceWindow variable = null (see code below) but I do not know how to get around this!
Any help much appreciated.
Andrew
code examples:
debugger.js:
var traceWindow = null
function opentraceWindow()
{
traceWindow = window.open('traceWindow.asp','traceWindow','width=400,height=800')
}
function sendToTracewindow(sCaller, pMessage)
{
try
{
if (!traceWindow)
{
opentraceWindow()
}
if (!traceWindow.closed)
{
var currentTrace = traceWindow.document.getElementById('trace').value
var newTrace = sCaller + ":" + pMessage + "\n" + currentTrace
traceWindow.document.getElementById('trace').value = newTrace
}
}
catch(e)
{
var currentTrace = traceWindow.document.getElementById('trace').value
var newTrace = "error tracing:" + e.message + "\n" + currentTrace
traceWindow.document.getElementById('trace').value = newTrace
}
}
traceWindow.asp - just a textarea with id='trace':
<HTML>
<head>
<title>Debug Window</title>
</head>
<body>
<textarea id="trace" rows="50" cols="50"></textarea>
</body>
</HTML>
I don't think there is any way around the fact that your traceWindow variable will be reset on every page load, therefore rendering your handle to the existing window invalid. However, if you don't mind leveraging LocalStorage and some jQuery, I believe you can achieve the functionality you are looking for.
Change your trace window to this:
<html>
<head>
<title>Debug Window</title>
<script type="text/javascript" src="YOUR_PATH_TO/jQuery.js" />
<script type="text/javascript" src="YOUR_PATH_TO/jStorage.js" />
<script type="text/javascript" src="YOUR_PATH_TO/jquery.json-2.2.js" />
<script type="text/javascript">
var traceOutput;
var traceLines = [];
var localStorageKey = "traceStorage";
$(function() {
// document.ready.
// Assign the trace textarea to the global handle.
traceOutput = $("#trace");
// load any cached trace lines from local storage
if($.jStorage.get(localStorageKey, null) != null) {
// fill the lines array
traceLines = $.jStorage.get(localStorageKey);
// populate the textarea
traceOutput.val(traceLines.join("\n"));
}
});
function AddToTrace(data) {
// append the new trace data to the textarea with a line break.
traceOutput.val(traceOutput.val() + "\n" + data);
// add the data to the lines array
traceLines[tracelines.length] = data;
// save to local storage
$.jStorage.set(localStorageKey, traceLines);
}
function ClearTrace() {
// empty the textarea
traceOutput.val("");
// clear local storage
$.jStorage.deleteKey(localStorageKey);
}
</script>
</head>
<body>
<textarea id="trace" rows="50" cols="50"></textarea>
</body>
</html>
Then, in your pages where you want to trace data, you could modify your javascript like so:
var traceWindow = null;
function opentraceWindow() {
traceWindow = window.open('traceWindow.asp','traceWindow','width=400,height=800');
}
function sendToTracewindow(sCaller, pMessage) {
traceWindow.AddToTrace(sCaller + ":" + pMessage);
}
Every time a new page is loaded and the trace window is refreshed, the existing trace data is loaded from local storage and displayed in your textarea. This should achieve the functionality that you are looking for.
Please be kind on any errors - I'm winging this on a Monday morning!
Finding the jQuery library should be trivial. You can find the jStorage library here: http://www.jstorage.info/, and you can find jquery-json here: http://code.google.com/p/jquery-json/

Resources