<jupyter_start><jupyter_text>Getting Started with Flask--- Content- What is it? How to install it? - How to write a basic Flask application- Jinja and templates- APIs. Creating them, using them- (Optional) Deploying a Flask app. with Docker --- What is it?[Flask](http://flask.pocoo.org/) is a minimal web framework for Python. One of its advantages is the extensive documentation as well as the number of plugins available for it. It uses the [Jinja2](http://jinja.pocoo.org/) templating engine to render HTML objects and can easily be integrated with web toolkits like [Bootstrap](https://getbootstrap.com/), to make consistent and responsive HTML layouts. --- How to write a basic Flask applicationFlask applications are meant to run on a command-line as a python script. This means that all the code we will write should be done _outside_ of this notebook.It is also common practice to create a file structure for the application that will help developing it in a much easier and organized. This will all make more sense as we move along but for now, create a new folder with the following file structure inside:```my-app/    │   app.py    │   config.py    │   requirements.txt     └── static/    └── templates/```The name of the application `my-app` can be anything you want.| File | Usage ||:---- |:---- || `app.py` | Contains all the python code your application will execute || `config.py` | Contains configuration variables related to Flask, plugins or your libraries || `requirements.txt` | Contains the python library requirements for your application to run || `static/` | This directory will store the public files that will be "server" through your app || `template` | This directory will contain all the Jinja2 templates | The follwing block of code is meant to be your first Flask application and it goes inside the `app.py` file. Copy and paste the code into that file (create it if it doesn't exist already). ```Pythonfrom flask import Flaskapp = Flask(__name__)@app.route('/hello')def hello_world():    return 'Hello World!'if __name__ == '__main__':    app.run()``` Note: `@app.route('/')` is a Python [decorator](https://www.python.org/dev/peps/pep-0318/) that associates the web address with respect to your root web domain and the function defined under it. Every time someone goes to the root web address ('/') of your application, this function is executed.In order to run your Flask application, open a terminal inside your application root directory and execute:- `python app.py`This message should be displayed if everything went well: `Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)`That will start a local web server, so if you click or go to that web address you should see the result of first web application!     Exercise:                 Write different routes and functions to display different content on each one. Test them by running the Flask server and point your browser to each new route.                 --- TemplatesFlask supports a very flexible and powerful HTML templating engine called Jinja2. With it, you can pass dynamic content into HTML and it's part of the reason why people find minimal web frameworks like Flask so useful.But first we need a minimal review of HTML in general ```HTML		Hello, world!	Hello        This is some text``` A suggested Bootstrap minimal HTML file ```HTML                              Hello, world!                                                    Hello                                This is some text                                                   ``` We can render those HTML templates with `Flask` using `render_template` ```Pythonfrom flask import Flask, render_templateapp = Flask(__name__)@app.route('/bootstrap')def bootstrap():    return render_template('minimal_bootstrap.html')@app.route('/minimal')def minimal():    return render_template('minimal.html')if __name__ == '__main__':    app.run()``` How do we pass information from Flask to the HTML template? Using special "place holder" tags inside the HTML that Jinja2 will process once Flask calls the `render_template` function. There are 4 main tags that Jinja2 will process:    {% ... %} for Statements    {{ ... }} for Expressions to print to the template output    { ... } for Comments not included in the template output      ...  for Line Statements ```HTML                              Hello, world!                             {{ content.company }} from {{ content.country }}                            Use this document as a way to quickly start any new project.            Find examples of objects and layouts here                                            ``` Note the `{{ }}` tags inside the HTML code. This are tags that Jinja2 will process and fill with the apropiate variables passed from Flask. Below is a new version of the code that should go inside `app.py` in order to pass the information that Jinja expects to render the template correctly. ```Pythonfrom flask import Flask, render_templateapp = Flask(__name__)@app.route('/jinja_template')def jinja_template():    dictionary = {'company': 'Agile', 'country': 'Canada'}    image_location = 'http://bit.ly/2mY5YUz'    return render_template('jinja_template.html', logo=image_location, content=dictionary)if __name__ == '__main__':    app.run()```     Exercise:                 Use `numpy` to make numerical calculations and return the results to your template!                 Let's now do something even better. Let's generate an new image everytime we access one of the views and display it on the template! ```Pythonimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinepoints = np.random.rand(10)plt.plot(points)plt.savefig("static/myfig.png")```     Exercise:                 Incorporate the previous code into your `app.py` to store an image inside the directory `static/` and display it on your template!                 If you're feeling confident, take it one step further!     Exercise:                 Write a function to make a LAS plot using matplotlib and any other library you may need and display it on the `index.html` template.                 You can also pass to your template lists of elements. This is useful if you have a number of objects that are meant to be displayed with the same style like a list. The Jinja2 tags that handle this are:```HTML{% for element in elements %}    {{ element }} says: {{ element }}{% endfor %}```Let's put that HTML code back in our template and modify `app.py` to pass a list call `elements` to it! ```Pythonfrom flask import Flask, render_templateapp = Flask(__name__)@app.route('/')def index():    content = {'company': 'Agile', 'country': 'Canada'}    logo = '/static/logo.png'    elements = ['One', 'Two', 'Three']    return render_template('index.html', logo=logo,                           content=content, elements=elements)@app.route('/hello')def hello_world():    return 'Hello World!'if __name__ == '__main__':    app.run()``` --- APIsAn application programming interface (API) is used to make simple the communication between computer programs or services. APIs remove the need for users to have to understand or compile a program in order to use it. This makes developing software that depends or uses third party services much easier. In the case of web APIs, almost every major web service has an API waiting for requests to use their services.|   HTTP |   Action | |---------|---------|| GET |  Retrieve || POST | Create || PUT | Update || DELETE | Delete |To understand how to use a simple API, we will make requests to `curvenam.es`API. This particular API serves as a lookup tool of wireline log mnemonics. First we need to load helper libraries `requests` and `json` to communicate with the [RESTful](https://en.wikipedia.org/wiki/Representational_state_transfer) API. To install `requests` we can use either `conda` or `pip`:- `conda install requests`- `pip install requests`The `json` library is standard and comes with the Python installation.<jupyter_code>import requests

# The following line makes a GET request to the API
payload = {'mnemonic': 'GR', 'method': 'fuzzy'}
response = requests.get('http://curvenam.es/lookup', params=payload)
# json.loads() parses the response and makes a Python dict object
response_dict = response.json()<jupyter_output><empty_output><jupyter_text>Part of the key in APIs is the documentation. To use them, you need to know what is needed in a request in order for it to be sucessful. In the case of `curvenam.es`, the API entry point or web address is `http://curvenam.es/lookup` and requires the keywords `mnemonic`, `method`, `limit` and `maxdist` to be specified. The syntax is the same for any `RESTful` API: `API_entry_point?keyword1=value1&keyword2=value2` and so on, for other keywords.<jupyter_code>response_dict<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08636931108841221, 'fraction_numerical': 0.0034048348655090228, 'mean_word_length': 3.482197355035605, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 3, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 1, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '294720', 'license': 'Apache-2.0', 'n_tokens_mistral': 2200, 'n_tokens_neox': 2137, 'n_words': 1120, 'path': 'notebooks/Flask_getting_started.ipynb', 'repo_name': 'michael-scarn/geocomp-0118', 'size': '8811'}