Browse Source

mongodb to json, new voting add support

pull/2/head
Efe Aydın 6 years ago
committed by GitHub
parent
commit
1f527af0a0
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 60 additions and 25 deletions
  1. +60
    -25
      server_side/api/voting_system/app.py

+ 60
- 25
server_side/api/voting_system/app.py View File

@ -1,46 +1,81 @@
import os
import ssl
import json
from flask import Flask
from flask_restful import Resource, Api, reqparse, abort
from pymongo import MongoClient
from bson.objectid import ObjectId
from flask import Flask, send_from_directory
from flask_restful import Resource, Api, abort, reqparse
app = Flask(__name__)
api = Api(app)
client = MongoClient("mongodb+srv://mycity:mycity123@mycity-3v9y3.mongodb.net/test?retryWrites=true", ssl_cert_reqs=ssl.CERT_NONE)
db = client.voting_system
collection = db.votings
parser = reqparse.RequestParser()
parser.add_argument('name')
parser.add_argument('desc')
parser.add_argument('img')
parser.add_argument('votes')
with open(os.path.join(app.root_path, 'votings.json'), 'r') as f:
votings_json = json.load(f)
votings = {
v['id']: v
for v in votings_json
}
class Votings(Resource):
def get(self):
votings = [
voting = [
{
'id' : str(doc['_id']),
'name': doc['name'],
'desc': doc['desc'],
'img' : doc['img']
'id' : v['id'],
'name': v['name'],
'desc': v['desc'],
'img' : v['img']
}
for doc in collection.find({})
for k, v in votings.items()
]
return votings
return voting
def post(self):
args = parser.parse_args()
voting_id = max(votings.keys()) + 1
voting = {
'id': voting_id,
'name': args['name'],
'desc': args['desc'],
'img' : args['img'],
'votes': [
{
'id': k,
'name': vote['name'],
'desc': vote['desc'],
'votes': 0
}
for k, vote in enumerate(json.loads(args['votes']))
]
}
votings[voting_id] = voting
votings_json.append(voting)
with open(os.path.join(app.root_path, 'votings.json'), 'w') as f:
json.dump(votings_json, f, indent=4)
return voting
class Vote(Resource):
class Voting(Resource):
def get(self, voting_id):
try:
doc = collection.find_one({'_id': ObjectId(voting_id)})
doc['_id'] = str(doc['_id'])
return {
k.replace('_id', 'id'): v
for k, v in doc.items()
}
return votings[voting_id]
except:
abort(404, error="Voting {} doesn't exist".format(voting_id))
api.add_resource(Votings, '/votings')
api.add_resource(Vote, '/votings/<voting_id>')
api.add_resource(Votings, '/votings', '/votings/')
api.add_resource(Voting, '/votings/<int:voting_id>')
@app.route('/img/<path:path>')
def send_img(path):
return send_from_directory('images', path)
if __name__ == '__main__':
app.run(debug=True)
app.run(host='0.0.0.0', port=5000, debug=True)

Loading…
Cancel
Save