0

I am now developing a web service. I choose Flask as the back end server and the Angularjs as the front end. I am still very new to web development.

In my infrastructure, if clients and the server want to exchange info, they will use REST Api and communicate with JSON files.

Now I want a new feature from the client side. I want to make the client can check the content a file on server and do auto refresh every 10s just in case the content of the file on server changes.

What method people usually use to query file contents from server. I don't think put all content into the a JSON file and use the same API I am using is a good way to do it.

Shanpei Zhou
  • 371
  • 1
  • 2
  • 17

1 Answers1

0

The good news is that you're definitely not the first person to need something like this! What you're describing can be done using the etag header, or the if-modified-since header. The bad news is, this isn't default behavior in flask, so we may have to mix it up a little.

Let's create a route which checks the last time a file was modified. If it hasn't been modified since then, it won't return anything. If it has, it'll send the file down.

@app.route('/api/files/modifiedSince')
def api_files_modified_since_get():
    # Get the date the user is requesting and the file they want
    modified_since, file_requested = request.args.get('since', None), file_requested = request.args.get('file', None)

    # If they didn't request anything, return an error
    if None is in [file_requested, modified_since]:
        app.abort(500)

    # Else, look it up, start by checking if the file even exists
    if not os.exists(file_requested):
        return "Invalid file!"

    # Check its modified since date
    (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file_requested)
    last_modified = str(time.ctime(mtime))

    if last_modified == modified_since:
        # The file hasn't changed, send back nothing
        return ""

    # Otherwise, send back the file!
    response = make_response(send_file(file_requested))
    response.headers.add('x-modified-time', last_modified)

    return response

Great! So our logic is in there, and we've got the last_modified time coming back in the header of the request. You're all good to go! But you may need more fine grained control in order to see the headers of the request. To do this I recommend more SO, he's a related question: jQuery and AJAX response header

Good luck!

Community
  • 1
  • 1
pmccallum
  • 808
  • 7
  • 14
  • Thanks! Actually the file on server will only be appended. Every time I only want to transfer the part that hasn't on client side. Are there any efficient way to do this? – Shanpei Zhou Sep 18 '15 at 17:02