Search code examples
pythonflaskapi-doc

How would I serve this html file with Flask (nota a template)


I'm using apidoc to generate a documentation website. On running, it creates a folder called doc, which contains an index.html file and accompanying css and js.

I'd like to be able to serve this folder with a Flask server, but can't work out how to do it.

My folder structure looks like this

-root
--- doc/ #contains all of the static stuff
--- server.py

I've tried this, but can't get it to work:

app = Flask(__name__, static_url_path="/doc")

@app.route('/')
def root():
    return app.send_from_directory('index.html')

One of the problems is that all of the static files referenced in the index.html generated by apidoc are relative to that page, so /js/etc. doesn't work, since it's actually /doc/js...

It would be great if someone could help me with the syntax here. Thanks.


Solution

  • I spot three problems in code.

    a) you do not need to use static_url_path, as send_from_directory is independent of it

    b) when I try to run above code, and go to /, I get a AttributeError: 'Flask' object has no attribute 'send_from_directory' - this means translates to app.send_from_directory is wrong - you need to import this function from flask, ie from flask import send_from_directory

    c) when I then try to run your code, I get a TypeError: send_from_directory() missing 1 required positional argument: 'filename', which means send_from_directory needs another argument; it needs both a directory and a file

    Putting this all together you get something like this:

    from flask import Flask
    from flask import send_from_directory
    
    
    app = Flask(__name__)
    
    
    @app.route("/")
    def index():
        return send_from_directory("doc", "index.html")
    

    As a takeway (for myself):