I’m trying to run a local server for testing a D3.js HTML file. I used python -m http.server
to start the server, but I’m not sure how to access my HTML file through it.
How do I navigate to the right folder and view my file in a browser via the Python webserver? Any tips for serving static files correctly?
Yeah, I do this all the time for testing HTML/JS. First, I cd into the folder where my .html file is:
cd path/to/your/html
python -m http.server 8000
Then I open http://localhost:8000/yourfile.html
in the browser. The key is to make sure you’re in the correct directory when starting the server, Python serves whatever is in the current directory.
I usually go:
python3 -m http.server 8080
That lets me serve files from wherever I am. You can even start it from VSCode’s terminal.
If your file is in ~/projects/d3/index.html
, just go to that folder first and then hit http://localhost:8080/index.html. W
orks great with D3 since you avoid CORS issues.
I wrote a little script so I don’t forget:
# serve.py
import http.server
import socketserver
PORT = 8888
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("Serving at port", PORT)
httpd.serve_forever()
I drop this in any folder and run python serve.py. Makes my testing workflow a breeze when playing with local data files or JS libraries like D3.