Simple service with posting client ip to postgre
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
from flask import Flask, request
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
import os
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
def get_env_variable(name):
|
||||
try:
|
||||
return os.environ[name]
|
||||
except KeyError:
|
||||
message = "Expected environment variable '{}' not set.".format(name)
|
||||
raise Exception(message)
|
||||
|
||||
|
||||
# the values of those depend on your setup
|
||||
POSTGRES_URL = get_env_variable("POSTGRES_URL")
|
||||
POSTGRES_USER = get_env_variable("POSTGRES_USER")
|
||||
POSTGRES_PW = get_env_variable("POSTGRES_PW")
|
||||
POSTGRES_DB = get_env_variable("POSTGRES_DB")
|
||||
|
||||
DB_URL = 'postgresql+psycopg2://{user}:{pw}@{url}/{db}'.format(user=POSTGRES_USER, pw=POSTGRES_PW, url=POSTGRES_URL,
|
||||
db=POSTGRES_DB)
|
||||
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
|
||||
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # silence the deprecation warning
|
||||
|
||||
db = SQLAlchemy(app)
|
||||
|
||||
|
||||
class Clients(db.Model):
|
||||
_tablename__ = 'clients'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
userip = db.Column(db.String(12))
|
||||
|
||||
@app.route("/")
|
||||
def hello():
|
||||
if 'X-Forwarded-For' in request.headers:
|
||||
proxy_data = request.headers['X-Forwarded-For']
|
||||
ip_list = proxy_data.split(',')
|
||||
user_ip = ip_list[0] # first address in list is User IP
|
||||
|
||||
else:
|
||||
user_ip = request.remote_addr # For local development
|
||||
print(user_ip)
|
||||
dropalch(user_ip)
|
||||
return "Sup World!"
|
||||
|
||||
def dropalch(user_ip):
|
||||
newip = Clients(userip=user_ip)
|
||||
db.session.add(newip)
|
||||
db.session.commit()
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host='0.0.0.0')
|
||||
Reference in New Issue
Block a user