question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Can't load another script

See original GitHub issue

Hi! Recently I am learning SPA and brython. And I got a question while adding a python script dynamically to my SPA page, but it doesn’t work!

When i click ‘login’ div, hash will be change, then trigger EvenListen to return login() function, and the content of login function will be added to #ctn, the css can be loaded and work but not login.py. But If it is a separate page, like login.html, the login.py can be loaded and work.

The way i also try:

  • using document.createElement

    using document.createElement, then appendChild to the right id. Didn’t work.

  • reading code from file and add to script tag

    read the login.py and add the script tag, then use document <= script. but it still not work.

  • using html.script to append to the DOM, manually get the login.py

    read the script.src and ajax to get the login.py src manually, can see the login.py loaded on Chrome, but the bind event didn’t work.

So how can i add python script link or code dynamically and make it work? Any advice or help will be appreciate!

here is some of my code:

my SPA demo

<body onload="brython(1)">
    <div id="app"></div>
    <script type="text/python">
    from browser import window, document, html

    def login():        
        username = html.INPUT(type='text', placeholder='Username', id='username')
        password = html.INPUT(type='password', placeholder='Password', id='password')
        button = html.BUTTON('login', id='login-button')
        form = html.DIV(Class='form')
        form <= username + password + button

        container = html.DIV(Class='container')
        container <= html.H1('Welcome') + form
        ul = html.UL(Class='bg-bubbles')
        for i in range(10):
            ul <= html.LI()
        wrapper = html.DIV(Class='wrapper')
        wrapper <= container + ul

        eaf = html.DIV(Class='htmleaf-container')
        eaf <= wrapper
        css = html.LINK(rel='stylesheet', type='text/css', href='assets/css/login.css')
        
        # This line can't work, the login.py can't be loaded but the login.css can.
        sct = html.SCRIPT(id='ascript', type='text/python3', src='login.py')
        
        # This line can be loaded, and it also work.
        #sct = html.SCRIPT(id='ascript', type='text/javascript', src='test.js')
        return eaf + css + sct

    def route():
        return {
            r'/login': {'handler': login, 'needAuth': True},
        }

    def routing(evt):
        pathname = get_path()
        tgt = route().get(pathname, None)
        if tgt:
            htmlstr = tgt.get('handler')()
            need_auth = tgt.get('needAuth')
        else:
            htmlstr = not_found()
            need_auth = False

        if need_auth:
            if not authed():
                htmlstr = login()

        print(type(htmlstr))

        if isinstance(htmlstr, str):
            document['ctn'].innerHTML = htmlstr
        else:
            document['ctn'].clear()
            document['ctn'] <= htmlstr

    def register():
        document['app'] <= html.DIV(id='nav')
        document['app'] <= html.DIV(id='ctn')
        for path in route().keys():
            document['nav'] <= html.DIV(path, onclick='window.location.href="#%s"' % path)
        document['nav'] <= html.DIV('/no_exist', onclick='window.location.href="#%s"' % '/asdfa')
        window.addEventListener('hashchange', routing)

    register()
    </script>
</body>

login.py

from browser import ajax
from browser import alert
from browser import document
from browser import html
from browser.session_storage import storage
import json

def encrypt(key):
    from hashlib import md5
    return md5(key.encode()).hexdigest()

def get_token():
    try:
        token = storage['token']
    except:
        return False
    else:
        return token


def logout():
    del storage['token']


def logged():
    return True if get_token() else False


@document['login-button'].bind('click')
def login(event):
    username = document['username'].value
    password = document['password'].value
    url = 'http://192.168.56.101:9999/login'
    if username and password:
        req = ajax.ajax()
        req.bind('complete', on_complete)
        # send a POST request to the url
        req.open('POST', url, True)
        req.set_timeout(6)
        # req.set_header('content-type', 'application/x-www-form-urlencoded')
        # send data as a dictionary
        data = json.dumps({'username': username, 'password': encrypt(password)})
        req.send(data)
    else:
        alert('plz input username and password')


def on_complete(req):
    auth = False
    alert(logged())
    if req.text is not None:
        res = json.loads(req.text)
        if res['code'] == 1 and res['msg'] == 'success' and res['token'] is not None:
            auth = True
            storage['token'] = res['token']
            from browser import window
            window.location.href = '/dashboard.html'

login.html

<!doctype html>
<html lang="cn">
<head id="head">
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Login</title>
	<link rel="stylesheet" type="text/css" href="assets/css/login.css">
 	<script type="text/javascript"
    src="https://cdn.rawgit.com/brython-dev/brython/master/www/src/brython.js"></script>
        <script type="text/javascript"
    src="https://cdn.rawgit.com/brython-dev/brython/master/www/src/brython_stdlib.js"></script>
</head>
<body onload="brython(1)">
<div class="htmleaf-container">
	<div class="wrapper">
		<div class="container">
			<h1>Welcome</h1>
			<div class="form">
				<input type="text" placeholder="Username" id="username">
				<input type="password" placeholder="Password" autocomplete="off" id="password">
				<button id="login-button">Login</button>
			</div>
		</div>
		
		<ul class="bg-bubbles">
			<li></li>
			<li></li>
			<li></li>
			<li></li>
			<li></li>
			<li></li>
			<li></li>
			<li></li>
			<li></li>
			<li></li>
		</ul>
	</div>
</div>
<script id="loginscript" type="text/python" src="login.py"></script>
</body>
</html>

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:12 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
PierreQuentelcommented, Apr 14, 2018

I meant the latest version, the one you can get with

<script type="text/javascript" src="https://cdn.rawgit.com/brython-dev/brython/master/www/src/brython.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/brython-dev/brython/master/www/src/brython_stdlib.js"></script>
0reactions
Ordielcommented, Sep 28, 2019

window.brython(1) # this runs the Brython engine on all <script type="text/python"> tags

This little piece should be documented somewhere a bit more visible, I was not able to find it anywhere on the documentation. Am I mistaken?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Loading another script from a Javascript file but I can't access ...
The issue seems to be that Javascript loads files asynchronously, so I was attempting to call the method before it was loaded. AJAX...
Read more >
Can't run script after another script is completely loaded
Tried with callbacks, async await and nothing works :confused: Basically I have inside a conditional the following code var CarouselScript ...
Read more >
Why can't I call function from another script? - Unity Answers
Hi people, just wondering if you could have a look at my script. I'm trying to call over a function from another script...
Read more >
Cannot load script at - WordPress.org
When I open the page is appearing this error: Setting up fake worker failed: “Cannot load script at: https://unilins.edu.br/wp-content/cache/autoptimize/js/ ...
Read more >
4. Loading Scripts Without Blocking - Even Faster Web Sites ...
When these opportunities arise, we want to load the JavaScript in such a way that it does not block other downloads. Luckily, there...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found