Commit 51f00494 authored by danmcquillan's avatar danmcquillan

added lab-13

parent 10a382be
static/uploads/*
*.pyc
from flask import Flask
from flask import make_response
from flask import render_template
from flask import request
import feedparser
import json
import urllib
import urllib2
import datetime
app = Flask(__name__)
RSS_FEEDS = { 'bbc': 'http://feeds.bbci.co.uk/news/rss.xml',
'cnn': 'http://rss.cnn.com/rss/edition.rss'}
DEFAULTS = {'publication':'bbc',
'city':'London, UK',
'currency_from' : 'GBP',
'currency_to' : 'USD'}
WEATHER_URL = 'http://api.openweathermap.org/data/2.5/' \
'weather?q={}&units=metric&appid=9504c0c840ef1f147f111a088b290341'
CURRENCY_URL = 'https://openexchangerates.org//api/latest.json?' \
'app_id=3435756597b94d05aab8e63e46551e30'
def get_news(query):
if not query or query.lower() not in RSS_FEEDS:
publication = "bbc"
else:
publication = query.lower()
feed = feedparser.parse(RSS_FEEDS[publication])
return feed['entries']
def get_weather(query):
query = urllib.quote(query)
url = WEATHER_URL.format(query)
data = urllib2.urlopen(url).read()
parsed = json.loads(data)
weather = None
if parsed.get("weather"):
weather = {"description":
parsed["weather"][0]["description"],
"temperature":parsed["main"]["temp"],
"city":parsed["name"],
'country': parsed['sys']['country']
}
return weather
def get_rate(frm, to):
all_currency = urllib2.urlopen(CURRENCY_URL).read()
parsed = json.loads(all_currency).get('rates')
frm_rate = parsed.get(frm.upper())
to_rate = parsed.get(to.upper())
return (to_rate/frm_rate, parsed.keys())
def get_values_with_fallback(key):
if request.args.get(key):
return request.args.get(key)
if request.cookies.get(key):
return request.cookies.get(key)
@app.route("/")
def home():
# get customized headlines, based on user input or default
publication = get_values_with_fallback('publication')
articles = get_news(publication)
# get customized weather based on user input or default
city = get_values_with_fallback('city')
weather = get_weather(city)
# get customized currency based on user input or default
currency_from = get_values_with_fallback("currency_from")
currency_to = get_values_with_fallback("currency_to")
rate, currencies = get_rate(currency_from, currency_to)
response = make_response(render_template("home.html",
articles=articles,
weather=weather,
currency_from=currency_from,
currency_to=currency_to,
rate=rate,
currencies=sorted(currencies)))
expires = datetime.datetime.now() + datetime.timedelta(days=365)
response.set_cookie("publication", publication, expires=expires)
response.set_cookie("city", city, expires=expires)
response.set_cookie("currency_from",
currency_from, expires=expires)
response.set_cookie("currency_to", currency_to, expires=expires)
return response
if __name__ == '__main__':
app.run(port=5000, debug=True)
from flask import Flask
from flask import render_template, session, request
from flask import redirect, url_for, flash
from flask import send_from_directory
import os
from vs_url_for import vs_url_for
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
UPLOAD_FOLDER = 'static/uploads'
app = Flask(__name__)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
# defining allowed file types for file upload
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def index():
files = [os.path.join(UPLOAD_FOLDER,f) for f in os.listdir(UPLOAD_FOLDER)]
return render_template('upload_index.html', files=files)
@app.route('/upload', methods = ['GET','POST'])
def upload_image():
if request.method == 'POST':
if 'file' not in request.files:
flash('no file part')
return redirect(request.url)
file = request.files['file']
if file.filename=='':
flash('no selected file')
return redirect(request.url)
if not allowed_file(file.filename):
flash('file type not allowed')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(UPLOAD_FOLDER,filename))
flash('File "{}" successfully uploaded'.format(filename))
return redirect(vs_url_for('index'))
return render_template('file_upload.html')
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0',port=8000)
from flask import Flask
from flask import render_template, session, request
from flask import redirect, url_for, flash
from flask import send_from_directory
import os
from werkzeug.utils import secure_filename
from vs_url_for import vs_url_for
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed, FileRequired
from wtforms import SubmitField
from wtforms import validators
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
UPLOAD_FOLDER = 'static/uploads'
class UploadForm(FlaskForm):
file = FileField('image', validators=[
FileRequired(),
FileAllowed(['jpg','png'], 'Images only!')])
submit = SubmitField('submit', [validators.DataRequired()])
app = Flask(__name__)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
@app.route('/')
def index():
files = [os.path.join(UPLOAD_FOLDER,f) for f in os.listdir(UPLOAD_FOLDER)]
return render_template('upload_index.html', files=files)
@app.route('/upload', methods = ['GET','POST'])
def upload_image():
form = UploadForm()
if form.validate_on_submit():
upload = form.file.data
filename = secure_filename(upload.filename)
upload.save(os.path.join(UPLOAD_FOLDER,filename))
flash('File "{}" successfully uploaded'.format(filename))
return redirect(vs_url_for('index'))
return render_template('file_upload_wtforms.html',form=form)
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0',port=8000)
from flask import Flask, render_template
from flask import request
import feedparser
app = Flask(__name__)
RSS_FEEDS = { 'bbc': 'http://feeds.bbci.co.uk/news/rss.xml',
'aljazeera' : 'https://www.aljazeera.com/xml/rss/all.xml',
'ap':\
'http://hosted2.ap.org/atom/APDEFAULT/cae69a7523db45408eeb2b3a98c0c9c5'}
@app.route("/")
def headlines():
publication =''
if request.args.get('publication'):
publication = request.args.get('publication')
if not publication or publication.lower() not in RSS_FEEDS:
publication = "bbc"
else:
publication = publication.lower()
feed = feedparser.parse(RSS_FEEDS[publication])
articles = feed['entries']
return render_template('get_headlines.html',articles=articles)
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0',port=8000)
from flask import Flask, render_template
from flask import request
import feedparser
app = Flask(__name__)
RSS_FEEDS = { 'bbc': 'http://feeds.bbci.co.uk/news/rss.xml',
'aljazeera' : 'https://www.aljazeera.com/xml/rss/all.xml',
'ap':\
'http://hosted2.ap.org/atom/APDEFAULT/cae69a7523db45408eeb2b3a98c0c9c5'}
@app.route("/")
def headlines():
publication = request.args['publication']
if not publication or publication.lower() not in RSS_FEEDS:
publication = "bbc"
else:
publication = publication.lower()
feed = feedparser.parse(RSS_FEEDS[publication])
articles = feed['entries']
return render_template('get_headlines.html',articles=articles)
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0',port=8000)
from flask import Flask, render_template
from flask import request, flash
import string
app = Flask(__name__)
USERNAME, PASSWORD = 'alan', '4l4n'
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
def sanitise_string(userinput):
return ''.join(e for e in userinput if e.isalnum())
# https://docs.python.org/3.5/library/stdtypes.html
@app.route("/", methods = ['GET','POST'])
def show_user():
username, password ='',''
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
username = sanitise_string(username)
password = sanitise_string(password)
if username == USERNAME and password == PASSWORD:
flash('login successful!')
list = [username, password]
return render_template('mock_login.html', list=list)
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0',port=8000)
from flask import Flask, render_template
from flask import request, flash
import string
app = Flask(__name__)
USERNAME, PASSWORD = 'alan', '4l4n'
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
def sanitise_string(userinput):
return ''.join(e for e in userinput if e.isalnum())
# https://docs.python.org/3.5/library/stdtypes.html
@app.route("/")
def show_user():
username, password ='',''
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
username = sanitise_string(username)
password = sanitise_string(password)
if username == USERNAME and password == PASSWORD:
flash('login successful!')
list = [username, password]
return render_template('mock_login.html', list=list)
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0',port=8000)
from flask import Flask, render_template
from flask import request, flash
import string
from flask_wtf import Form
from wtforms import PasswordField
from wtforms import StringField
from wtforms import SubmitField
from wtforms import validators
class LoginForm(Form):
username = StringField('username', validators = [validators.DataRequired()])
password = PasswordField('password', validators =[validators.DataRequired(), validators.length(min=8)])
password2 = PasswordField('password2', validators=[validators.DataRequired(),
validators.EqualTo('password', message='Passwords must match')])
submit = SubmitField('submit', [validators.DataRequired()])
app = Flask(__name__)
USERNAME, PASSWORD = 'alan', '4l4n4l4n'
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
def sanitise_string(userinput):
return ''.join(e for e in userinput if e.isalnum())
# https://docs.python.org/3.5/library/stdtypes.html
@app.route('/', methods = ['GET', 'POST'])
def login():
username, password ='',''
form = LoginForm()
if form.validate_on_submit():
password = form.password.data
username = form.username.data
if username == USERNAME and password == PASSWORD:
flash('login successful!')
list = [username, password]
return render_template('mock_login_wtforms.html', form=form, list=list)
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0',port=8000)
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
img {
height: 200px;
}
</style>
</head>
<body>
<div class="container">
{% for category, message in get_flashed_messages(with_categories=true) %}
<div class="alert alert-dismissable alert-warning alert-{{ category }}">
<button type="button" class="close" data-dismiss="alert">&times;</button>
{{ message }}
</div>
{% endfor %}
<div class="jumbotron">
{% block body %}{% endblock %}
</div>
</div>
</body>
</html>
<html>
<head>
<title>Headlines</title>
<style>
html {
font-family: "Helvetica";
background: white;
}
body {
background: lightgrey;
max-width: 900px;
margin: 0 auto;
}
#header {
padding-top: 5;
background: lightsteelblue;
}
#inner-header {
padding-left: 10;
}
#main{
padding-left: 10;
}
input[type="text"], select {
color: grey;
border: 1px solid lightsteelblue;
height: 30px;
line-height:15px;
margin: 2px 6px 16px 0px;
}
input[type="submit"] {
padding: 5px 10px 5px 10px;
color: black;
background: lightsteelblue;
border: none;
box-shadow: 1px 1px 1px #4C6E91;
}
input[type="submit"]:hover{
background: steelblue;
}
</style>
</head>
<div id="header">
<div id="inner-header">
<h1>Headlines</h1>
<p>Headlines. Currency. Weather.</p>
</div>
<hr />
</div>
<div id="main">
<h2>Current weather</h2>
<p>City: <b>{{weather.city}}, {{ weather.country }}</b></p>
<p>{{weather.description}} |{{weather.temperature}}&#8451;</p>
<h2>Currency</h2>
<form>
from: <select name="currency_from">
{% for currency in currencies %}
<option value="{{currency}}" {% if currency_from==currency %} selected="selected" {% endif %} >
{{currency}}</option>
{% endfor %}
</select>
to: <select name="currency_to">
{% for currency in currencies %}
<option value="{{currency}}" {% if currency_to==currency %} selected="selected" {% endif %} >
{{currency}}</option>
{% endfor %}
</select>
<input type="submit" value="Submit">
</form>
{{currency_from}} = {{currency_to}} {{rate}}
<h2>Headlines</h2>
<body>
<form>
<input type="text" name="publication" placeholder="news search" />
<input type="submit" value="Submit" />
</form>
<form>
<input type="text" name="city" placeholder="weather search" />
<input type="submit" value="Submit" />
</form>
{% for article in articles %}
<b><a href="{{ article.link }}">{{article.title}}</a></b><br />
<i>{{article.published}}</i><br />
<p>{{article.summary}}</p>
<hr />
{% endfor %}
</div>
</body>
</html>
{% extends "upload_base.html" %}
{% block body %}
<h1>Upload new File</h1>
<form method='post' enctype='multipart/form-data'>
<p><input type='file' name='file'>
<input type='submit' value='Upload'>
</form>
{% endblock %}
{% extends "upload_base.html" %}
{% block body %}
<h1>Upload new File</h1>
<form class='form-horizontal' method='post' enctype='multipart/form-data'>
{{ form.csrf_token }}
<div class='form-group'>
<div class='col-md-6'>
{% if form.file.errors %}
<ul class='errors'>
{% for error in form.file.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
{{ form.file(class='form-control',placeholder='file') }}
</div>
</div>
<div class='form-group'>
<div class='col-md-6'>
{{ form.submit(class='btn btn-primary btn-block') }}
</div>
</div>
</form>
{% endblock %}
<html>
<head>
<title>Headlines</title>
</head>
<body>
<h1>Headlines</h1>
<form>
<input type="text" name="publication" placeholder="search for headlines" />
<input type="submit" value="Submit" />
</form>
{% for article in articles %}
<b>{{article.title}}</b><br />
<i>{{article.published}}</i><br />
<p>{{article.summary}}</p>
<hr />
{% endfor %}
</body>
</html>
{% extends "base.html" %}
{% block body %}
<a href='/upload'>upload</a>
{% for f in files %}
<div class="row">
<div class="col-md-12"><img src="{{ f }}" /></div>
</div>
{% endfor %}
{% endblock %}
{% extends "mock_login_base.html" %}
{% block body %}
<form method='post'>
<input type="text" name="username" placeholder="username" />
<input type="password" name="password" placeholder="password" />
<input type="submit" value="Submit" />
</form>
{% for item in list %}
<div class="row">
<div class="col-md-4 h2">{{ item }}</div>
<div class="col-md-4"></div>
<div class="col-md-4"></div>
</div>
{% endfor %}
{% endblock %}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
</style>
</head>
<body>
<div class="container">
{% for category, message in get_flashed_messages(with_categories=true) %}