Skip to content

Instantly share code, notes, and snippets.

@G-Goldstein
Last active March 4, 2019 14:02
Show Gist options
  • Save G-Goldstein/271a48ff61828b0e73ced6485987ba6c to your computer and use it in GitHub Desktop.
Save G-Goldstein/271a48ff61828b0e73ced6485987ba6c to your computer and use it in GitHub Desktop.

This is the source code for a small book catalogue app. The installation instructions are as follows:

  1. Install Python 3.7
  2. Place the app.py file into an install directory
  3. Run pip install flask
  4. Start the app using python app.py from within the install directory

You can then check that it's working by navigating to http://<your machine ip>:5000/api/v1/resources/books/all, where you should see a list of books.

import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
# Create some test data for our catalog in the form of a list of dictionaries.
books = [
{'id': 0,
'title': 'A Fire Upon the Deep',
'author': 'Vernor Vinge',
'first_sentence': 'The coldsleep itself was dreamless.',
'year_published': '1992'},
{'id': 1,
'title': 'The Ones Who Walk Away From Omelas',
'author': 'Ursula K. Le Guin',
'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.',
'published': '1973'},
{'id': 2,
'title': 'Dhalgren',
'author': 'Samuel R. Delany',
'first_sentence': 'to wound the autumnal city.',
'published': '1975'}
]
@app.route('/', methods=['GET'])
def home():
return '''<h1>Distant Reading Archive</h1>
<p>A prototype API for distant reading of science fiction novels.</p>'''
# A route to return all of the available entries in our catalog.
@app.route('/api/v1/resources/books/all', methods=['GET'])
def api_all():
return jsonify(books)
app.run(host="0.0.0.0")
FROM python:3.7
RUN pip install flask
RUN useradd api -m
# Set our current directory, so that we're not installing into /
WORKDIR /home/api/
# Change to the 'api' user now, to reduce permissions for security
USER api
# Tag our image as exposing this port; this is only metadata to describe how our image works
EXPOSE 5000
# Copy app.py into our working directory, with owner 'api'
COPY --chown=api:api app.py .
CMD ["python", "app.py"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment