This commit is contained in:
Benjamyn Love 2020-05-02 06:37:40 -04:00
commit 83e78fa725
5 changed files with 131 additions and 0 deletions

5
.config template Normal file
View File

@ -0,0 +1,5 @@
[mysql]
Host = localhost
Username = SQLUSERNAME
Password = SQLPASSWORD
Database = SQLDATABASE

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
__pycache__/
env/
.config

52
db.py Normal file
View File

@ -0,0 +1,52 @@
import mysql.connector
import configparser
config = configparser.ConfigParser()
try:
config.read(".config")
except Exception as E:
print(E)
def dbConnect():
mydb = mysql.connector.connect(
host=config["mysql"]["Host"],
user=config["mysql"]["Username"],
passwd=config["mysql"]["Password"],
database=config["mysql"]["Database"]
)
return mydb
def runQuery(query, data=None):
mydb = dbConnect()
c = mydb.cursor()
if data is not None:
c.execute(query, data)
else:
c.execute(query)
if query.lower().startswith("select"):
ret = c.fetchall()
else:
ret = []
mydb.commit()
mydb.close()
return ret
def checkIfPasteExists(id):
query = "SELECT id from pastes where id=%s"
if runQuery(query, (id,)):
return True
return False
def insertPaste(id, paste):
query = "INSERT into pastes (id, paste) values (%s, %s)"
runQuery(query, (id, paste))
def getPaste(id):
query = "select paste from pastes where id=%s"
return runQuery(query, (id,))

3
requirements.txt Normal file
View File

@ -0,0 +1,3 @@
flask
flask-cors
mysql-connector

68
server.py Normal file
View File

@ -0,0 +1,68 @@
from flask import Flask, request, make_response
from flask_cors import CORS
from pprint import pprint
import random
import string
import db
nameLength = 10
pastes = {}
application = Flask(__name__)
CORS(application)
application.config['DEBUG'] = False
letters = string.ascii_uppercase + string.ascii_lowercase + string.digits
def randomName():
name = ""
for x in range(0, nameLength):
x = x
num = random.randint(0, len(letters))
# print(num)
name += letters[num - 1]
return name
def savePaste(id, paste):
db.insertPaste(id, paste)
def loadPaste(id):
paste = db.getPaste(id)[0][0]
return paste
def generateUniqeName(id, works=False):
if id == None:
id = randomName()
if works == False:
id = randomName()
if db.checkIfPasteExists(id):
id = generateUniqeName(id, False)
return id
@application.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if request.headers.get('Content-Type') == 'application/json':
data = request.json
id = randomName()
id = generateUniqeName(id, True)
savePaste(id, data['paste'])
resp = make_response(id)
resp.headers['Content-Type'] = 'application/json'
return resp
return ''
@application.route('/<path:path>')
def getPaste(path):
print(path)
return loadPaste(path)
if __name__ == '__main__':
application.run()