Description: Get requests works fine. Example from python interpretator:
r = requests.get("http://openshift-XXXXXXXXX/get_all_posts")
r.text
'{"posts":[]}'
But the problem is to make the post requests: Ill give an example:
r = requests.post("http://openshift-XXXXXXXX/create_user", json={"username":"user","nickname":"nick", "password":"pass"})
r.text
'\n500 Internal Server Error\n
Internal Server Error
\nThe server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
\n'
Any help would be appreciated.
setup.py
from setuptools import setup
setup(name='YourAppName',
version='1.0',
description='OpenShift App',
author='Ludvig Westerdahl',
author_email='example@example.com',
url='http://ift.tt/LqW88y',
install_requires=['Flask','Flask-SQLAlchemy>=2.1', "sqlalchemy>=1.0.11"],
)
wsgi.py
#!/usr/bin/env python
import os
from magdb import app as application
virtenv = os.path.join(os.environ.get('OPENSHIFT_PYTHON_DIR','.'), 'virtenv')
if __name__ == '__main__':
from wsgiref.simple_server import make_server
httpd = make_server('localhost', 5002, application)
httpd.serve_forever()
magdb.py
from flask import Flask, json, jsonify, request, g
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import class_mapper
import os
from werkzeug.security import generate_password_hash, check_password_hash
from functools import wraps
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
from sqlalchemy import update
# --------------------------
# --- App creation START ---
# --------------------------
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'Will Will Smith smith? Yes... Will Smith will smith'
if "OPENSHIFT_POSTGRESQL_DB_URL" in os.environ:
app.config["SQLALCHEMY_DATABASE_URI"]=os.environ['OPENSHIFT_POSTGRESQL_DB_URL']
else:
app.config["SQLALCHEMY_DATABASE_URI"]="sqlite:////tmp/testmagdb.db"
db = SQLAlchemy(app)
# --------------------------
# --- App creation END -----
# --------------------------
friends_table = db.Table("friends_table",
db.Column("user_id", db.Integer, db.ForeignKey("user.id"), primary_key=True),
db.Column("friend_id", db.Integer, db.ForeignKey("user.id"), primary_key=True),
db.PrimaryKeyConstraint("user_id", "friend_id"))
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
# --- Creation of Account requirments ---
username = db.Column(db.String(25))
nickname = db.Column(db.String(25))
password = db.Column(db.String(50))
# --- Creation of profile ---
description_column = db.Column(db.String(255))
rating = db.Column(db.Integer)
#friends = db.relationship("User", backref=db.backref("users", lazy="dynamic"), secondary=friends_table)
my_friends = db.relationship('User',
secondary=friends_table,
primaryjoin=(friends_table.c.user_id == id),
secondaryjoin=(friends_table.c.friend_id == id),
backref=db.backref("friends_of_me", lazy='dynamic'),
lazy='dynamic')
liked_posts = []
dissliked_posts = []
token = db.Column(db.Text)
def __init__(self, username, nickname, password):
self.username = username
self.nickname = nickname
self.password = generate_password_hash(password)
self.rating = 0
def reset_token(self):
self.token = None
def set_token(self, token):
self.token = token
def get_token(self):
return self.token
def check_password(self, password):
return check_password_hash(self.password, password)
def generate_auth_token(self, experation=6000):
s = Serializer(app.config['SECRET_KEY'], expires_in=experation)
return s.dumps({'id':self.id})
# --- Profile management ---
def get_rating(self):
return self.rating
def mod_rating(self, rating):
self.rating += rating
def undo_rating(self, id):
self.rating = 0
"""
if id in self.dissliked_post_list:
self.rating += 1
self.dissliked_post_list.remove(id)
if id in self.liked_post_list:
self.rating -= 1
self.liked_post_list.remove(id)
"""
def get_description(self):
return self.description
def set_description(self, description):
self.description_column = description
def get_description(self):
return self.description_column
def to_json(self):
s = {"nickname":self.nickname, "description":self.description_column, "rating":self.rating}
return json.dumps(s)
#return json.dumps(dict(username=self.username))
def to_dict(self):
s = {"nickname":self.nickname, "description":self.description_column, "rating":self.rating}
return s
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50))
game = db.Column(db.String(50))
description = db.Column(db.String(255))
comment = db.Column(db.String(255))
owner = db.relationship('User', backref=db.backref('posts', lazy='dynamic'))
owner_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __init__(self, title, game, description, owner):
self.title = title
self.game = game
self.description = description
self.owner = owner
self.comment = ""
def add_comment(self, comment):
self.comment = self.comment + comment
def to_json(self):
# username va nickname förut
s = {"title": self.title, "game":self.game, "description":self.description, "owner": self.owner.username, "comments":self.comment}
return json.dumps(s)
def to_dict(self):
# username va nickname förut
s = {"title": self.title, "game":self.game, "description":self.description, "owner": self.owner.username, "comments":self.comment}
return s
@app.route('/set_description', methods=['POST'])
def set_description():
input = request.get_json()
user_id = input['user_id']
description = input['description']
user = db.session.query(User).filter(User.id == user_id).first()
user.set_description(description)
commit_db()
return "Description set", 200
@app.route('/remove_friend', methods=['POST'])
def remove_friend():
input = request.get_json()
user_id = input['user_id']
friend_username = input['friend_username']
user = db.session.query(User).filter(User.id == user_id).first()
friend = db.session.query(User).filter(User.username == friend_username).first()
try:
user.my_friends.remove(friend)
commit_db()
except:
return "Not friend", 400
return "Sucess removed friend", 200
@app.route('/add_friend', methods=['POST'])
def add_friend():
input = request.get_json()
user_id = input['user_id']
friend_username = input['friend_username']
user = db.session.query(User).filter(User.id == user_id).first()
friend = db.session.query(User).filter(User.username == friend_username).first()
try:
user.my_friends.append(friend)
commit_db()
except:
return "Already friend", 400
return "Sucess added friend", 200
@app.route('/get_all_friends/<int:user_id>', methods=['GET'])
def get_all_friends(user_id):
list_of_friends = []
user = db.session.query(User).filter(User.id == user_id).first()
for friend in user.my_friends:
list_of_friends.append(friend.to_dict())
return json.dumps({"friends": list_of_friends})
@app.route('/get_friend/<username>', methods=['GET'])
def get_friend(username):
friend = db.session.query(User).filter(User.username == username).first()
return friend.to_json()
@app.route('/get_rating/<user_id>', methods=['GET'])
def get_rating(user_id):
user = db.session.query(User).filter(User.id == user_id).first()
return str(user.rating), 200
@app.route('/comment', methods=['POST'])
def comment():
input = request.get_json()
comment = input['comment']
post_id = input['post_id']
post = db.session.query(Post).filter(Post.id == post_id).first()
post.add_comment(comment + "\n")
commit_db()
return "comment:" + comment + "added", 200
@app.route('/modify_rating', methods=['POST'])
def modify_rating():
input = request.get_json()
rating = input['rating']
# This is the post that they user has clicked like on
post_id = input['post_id']
post = db.session.query(Post).filter(Post.id == post_id).first()
# The input user-id is the one that is liking/dissliking something
user_id = input['user_id']
user = db.session.query(User).filter(User.id == user_id).first()
# User liked the post
print("HERE")
if rating == 1:
print("HERE1")
if post_id in user.dissliked_posts:
user.liked_posts.append(post_id)
user.dissliked_posts.remove(post_id)
post.owner.mod_rating(2)
print("HERE2")
elif not post_id in user.liked_posts:
user.liked_posts.append(post_id)
post.owner.mod_rating(1)
print("HERE3")
elif rating == -1:
print("HERE4")
if post_id in user.liked_posts:
user.dissliked_posts.append(post_id)
user.liked_posts.remove(post_id)
post.owner.mod_rating(-2)
print("HERE5")
elif not post_id in user.dissliked_posts:
user.dissliked_posts.append(post_id)
post.owner.mod_rating(-1)
print("HERE6")
elif rating == 0:
print("HERE7")
if post_id in user.liked_posts:
user.liked_posts.remove(post_id)
post.owner.mod_rating(-1)
print("HERE8")
elif post_id in user.dissliked_posts:
user.dissliked_posts.remove(post_id)
post.owner.mod_rating(1)
print("HERE9")
print(str(post.owner.rating))
db.session.commit()
print(str(post.owner.rating))
return "DONE", 200
@app.route('/get_post/<int:post_id>', methods=['GET'])
def get_post(post_id):
try:
post = db.session.query(Post).filter(Post.id == post_id).first()
return post.to_json(), 200
except:
return "Post doesnt exist", 400
#if not post == None:
# return post.to_json(), 200
@app.route('/get_all_posts', methods=['GET'])
def get_all_posts():
list_of_posts = []
for post in db.session.query(Post).all():
list_of_posts.append(post.to_dict())
return json.dumps({"posts": list_of_posts})
@app.route('/post', methods=['POST'])
def create_post():
input = request.get_json()
title = input['title']
game = input['game']
description = input['description']
owner_id = input['owner_id']
owner = db.session.query(User).filter(User.id == owner_id).first()
post = Post(title, game, description, owner)
db.session.add(post)
commit_db()
return "Post created", 200
@app.route('/login', methods=['POST'])
def login():
input = request.get_json()
username = input['username']
password = input['password']
user_trying_to_login = db.session.query(User).filter(User.username == username).first()
if user_trying_to_login == None:
print("Inside == none")
return "Username + password not matching", 400
print("----------BEFORE CHECK PASS------")
if user_trying_to_login.check_password(password):
print("----------INSIDE CHECK PASS------")
# return id so we know which one is logged in during the session from the app
return json.dumps({"id":user_trying_to_login.id}), 200
else:
print("----------INSIDE ELSE CHECK PASS------")
return "Username(else) + password not matching", 400
@app.route('/create_user', methods=['POST'])
def create_user():
input = request.get_json()
new_user = User(input['username'], input['nickname'], input['password'])
db.session.add(new_user)
commit_db()
return "user added", 200
# ---------------------------------
# ----- Db START ------------------
# ---------------------------------
def serialize(model):
columns = [c.key for c in class_mapper(model.__class__).columns] # Create a list from the columns.
return dict((c, getattr(model, c)) for c in columns) # Return a dictionary containing the columns.
def reset_db():
try:
db.drop_all()
db.session.commit()
except: #TEST
db.session.rollback() #TEST
def commit_db():
db.session.commit()
def init_db():
db.create_all()
# ---------------------------------
# ----- Db END --------------------
# ---------------------------------
db.create_all()
@app.route('/')
def hello_world():
return "/magdb"
if __name__ == '__main__':
#app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.run(debug=True, port=5002)
Basically, everything works fine on the local to the sqllite database. But then deploying to openshift, post requests gives the Internal Server Error
Aucun commentaire:
Enregistrer un commentaire