How to add CSS and JS files in core Python without using Flask & Django?


How to add CSS and JS files in core Python without using Flask & Django?



I'm a beginner in Python, I'm just learning Python now. I tried a lot for adding CSS & JS files in my basic form without using Flask & Django. How can I do this?





I think we would need to see some code to understand what you are doing. Generally CSS/Js files are served by the webserver, not python application code.
– snakecharmerb
Jun 30 at 7:14





Thank you so much for your response @snakecharmerb I will post the code now
– ravihas chenneboyina
Jun 30 at 7:17





1 Answer
1



For that, you need to output your CSS and JS file directly to the HTML file.
For example, if you have the folder structure as follows:



You can create a route to output the file by reading it, Please check following code



in your app.py file


import web
import os
routs = (
'/','index',
'/staticFiles','loadStatic'
)
app = web.application(routs, globals())
render = web.template.render('templates/',base="maintemplate")
class index(object):
def GET(self):
return render.demoform()
class loadStatic(object):
def GET(self):
form = web.input(fileName='',filePath='')
fileName=form.file
filePath=form.folder
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = ("../assets/%s/%s" % (filePath,fileName))
abs_file_path = os.path.join(script_dir, rel_path)
temp = open(abs_file_path,'r').read()
return temp



In your maintemplate.html


$def with (content)
<html>
<head>
<title> SAMPLE CODE </title>
<link rel="stylesheet" href="staticFiles?file=style.css&folder=css" />
<script src="staticFiles?file=myjs.js&folder=js"></script>
</head>
<body>
$:content
</body>
</html>



How It Works
In app.py, like all CDN CSS/JS links, we are reading the file and returning output to the browser as a HTTP request.





Thanks a lot @Ux Chandra it works!! :)
– ravihas chenneboyina
Jun 30 at 7:54






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Extract Id from Twitch Clip URL

Why are these constructs (using ++) undefined behavior in C?

I'm Still Waiting (Diana Ross song)