Beispiel #1
0
# -*- coding: utf-8 -*-

from flask import Flask, jsonify, url_for, redirect, request
from flask_pymongo import PyMongo
from flask_restful import Api, Resource

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "tareasDb"
mongo = PyMongo(app, config_prefix='MONGO')

"""Api rest para tareas, con titulo y descricipio. Titulo es la clave
"""
class Tarea(Resource):
    """Consultas get
    """
    def get(self, titulo=None, descripcion=None):
        data = []

        if titulo:
            tareas_info = mongo.db.tareas.find_one({"titulo": titulo}, {"_id": 0})
            if tareas_info:
                return jsonify({"status": "ok", "data": tareas_info})
            else:
                return {"response": "no hay datos para {}".format(titulo)}

        elif descripcion:
            cursor = mongo.db.tareas.find({"descripcion": descripcion}, {"_id": 0}).limit(10)
            data.append(tareas)

            return jsonify({"descripcion": descripcion, "response": data})
Beispiel #2
0
from flask import Flask, request, jsonify, render_template
from pymongo import MongoClient

import json
import urllib2


MONGODB_HOST = "localhost"
MONGODB_PORT = 27017

app = Flask(__name__)
app.config.from_object(__name__)
app.config["MONGO_DBNAME"] = "mainAPP"

# connection = MongoClient('localhost', 27017)
connection = MongoClient(app.config["MONGODB_HOST"], app.config["MONGODB_PORT"])


@app.route("/", methods=["GET"])
def index():
    db = connection["mainAPP"]
    collection = db.urls
    urls = collection.find()
    existing_urls = []

    for url in urls:
        usr = {"url": str(url["url"])}
        existing_urls.append(usr)

    return render_template("index.html", existing=json.dumps(existing_urls))
Beispiel #3
0
from flask import Flask, render_template, jsonify, url_for, redirect, request
from flask.ext.cors import CORS
from flask_pymongo import PyMongo
from flask_restful import Api, Resource
from data_builder.data_builder import *

# Create app and connect to MongoDB
application = Flask(__name__)
application.config["MONGO_HOST"] = "mongoContainer"
application.config["MONGO_DBNAME"] = "setlists"
application.config['SERVER_NAME'] = 'setlist.visualizer'
application.config["MONGO_CONNECT"] = False
mongo = PyMongo(application, config_prefix='MONGO')


# Get concert dates for available artist
class Shows(Resource):
    def get(self, artist=None):

        # If an artist is passed in, grab all shows from MongoDB.
        if artist:
            shows = get_shows(mongo, artist, request.args)
            if shows['total']:
                return jsonify({"status": "ok", "data": shows})
        return {"status": "fail", "data": "No shows found for artist {0}".format(artist)}


# Get list of all tours
class Tours(Resource):
    def get(self, artist=None):
Beispiel #4
0
from flask import Flask, jsonify, abort, render_template, Response
from flask.ext.pymongo import PyMongo


app = Flask(__name__)
app.config["MONGO_DBNAME"] = "bizdev"

mongo = PyMongo(app)


def renderTemplate(contents=None, title="", referrer=None):
    return render_template("index.html", title=title, content=contents, referrer=referrer)


def renderAmazonCategories():
    categories = uniqueAmazonCategories()
    return render_template("amazon.html", categories=categories)


@app.route("/")
def index():
    return renderTemplate(contents="<h3>Select a Site to view its sellers.</h3>", title="Home")


@app.route("/amazon")
def amazon():
    categories = renderAmazonCategories()
    contents = categories
    return renderTemplate(contents=contents, title="Amazon", referrer="amazon")

Beispiel #5
0
from lib.User import User
from lib.Config import Configuration
from lib.Toolkit import toStringFormattedCPE, toOldCPE, currentTime, isURL, vFeedName, convertDateToDBFormat
import lib.CVEs as cves
import lib.DatabaseLayer as db
from sbin.db_whitelist import *
from sbin.db_blacklist import *

# parse command line arguments
argparser = argparse.ArgumentParser(description="Start CVE-Search web component")
argparser.add_argument("-v", action="store_true", help="verbose output")
args = argparser.parse_args()

# variables
app = Flask(__name__, static_folder="static", static_url_path="/static")
app.config["MONGO_DBNAME"] = Configuration.getMongoDB()
app.config["SECRET_KEY"] = str(random.getrandbits(256))
pageLength = Configuration.getPageLength()

# login manager
login_manager = LoginManager()
login_manager.init_app(app)
# db connectors
redisdb = Configuration.getRedisVendorConnection()

# functions
def getBrowseList(vendor):
    result = {}
    if (vendor is None) or type(vendor) == list:
        v1 = redisdb.smembers("t:/o")
        v2 = redisdb.smembers("t:/a")
from flask import Flask, Response
from flask.ext.pymongo import PyMongo
import json
from settings import *

app = Flask(__name__)
app.config["MONGO_HOST"] = CONFIG["mongo"]["host"]
app.config["MONGO_DBNAME"] = CONFIG["mongo"]["db"]
if CONFIG["mongo"].has_key("uri"):
    app.config["MONGO_URI"] = CONFIG["mongo"]["uri"]

mongo = PyMongo(app)


@app.route("/palavra/<palavra>")
def define(palavra):
    dicionario = mongo.db[CONFIG["mongo"]["collection"]]
    resultado = dicionario.find_one_or_404({"palavra": palavra})
    resultado.pop("_id")
    resp = Response(json.dumps(resultado), status=200, mimetype="application/json")
    resp.headers["Access-Control-Allow-Origin"] = "*"
    return resp


if __name__ == "__main__":
    app.run(debug=True)
from flask import redirect
from flask import render_template
from flask import request
from flask import Response
from flask.ext.pymongo import PyMongo

from sqlalchemy import *
from sqlalchemy.pool import NullPool
from SketchLib.SketchRecogniser import sketch_recogniser

from SketchLib.PictureLib import picture_matcher
from SketchLib.PictureLib import save_to_png
from SketchLib.PictureLib import video_matcher

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "vdb_images"
app.config["MONGO_USERNAME"] = "JRK"
app.config["MONGO_PASSWORD"] = "weloveVDB"

mongo = PyMongo(app)

output_sketch = "static/img/sketch.png"
# output_sketch = "static/img/sketch"
copied_sketch = "static/img/copied.png"
background_file = "static/img/background.png"

picture_results = []
video_results = []

@app.route('/')
def index():
allowed upload formates
"""    
ALLOWED_EXTENSIONS = set(['jpg', 'jpeg'])

"""
ssl keys for the server
"""
SERVER_KEY = ""
SERVER_CRT = ""

app = Flask(__name__)

"""
configure some specific defaults for the app
"""
app.config["MONGO_DBNAME"] = "test"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MONGOALCHEMY_DATABASE'] = 'test'
"""
start db connector
"""
client = MongoClient()
db = client.test

collectionUsers = db.users
collectionPlaces = db.places


import FlaskWebProject1.dbHelper
import FlaskWebProject1.views
Beispiel #9
0
# -*- coding: utf-8 -*-

from flask import Flask, request, redirect, jsonify
from flask_pymongo import PyMongo
from flask_restful import Api, Resource
import stockio_mongo as database
import simplejson as json
import collections

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "stockio"
mongo = PyMongo(app, config_prefix="MONGO")
APP_URL = "http://0.0.0.0:5000"


class Financials(Resource):
    def get(self, symbol=None, fiscal_year=None, fiscal_quarter=None, search_term=None):

        response = database.query(symbol, fiscal_year, fiscal_quarter, search_term)

        sorted_response = []

        for dict in response:
            for x, y in dict.items():
                dict[x] = str(y)

            sorted_dict = collections.OrderedDict(sorted(dict.items()))
            sorted_response.append(sorted_dict)

        return sorted_response
Beispiel #10
0
from flask import Flask, render_template, request, redirect, abort
from flask.ext.pymongo import PyMongo
#from Flask-PyMongo import PyMongo
import pymongo
from bson.objectid import ObjectId
from pymongo import ASCENDING, DESCENDING

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "cats"
app.config["MONGO_HOST"] = "linus.mongohq.com"
app.config["MONGO_PORT"] = 10042
app.config["MONGO_USERNAME"] = "hello"
app.config["MONGO_PASSWORD"] = "world"
app.config["SECRET_KEY"] = "KeepThisS3cr3t"
app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 0
mongo = PyMongo(app)

@app.route('/')
def index():
    posts = mongo.db.posts.find().sort("views", DESCENDING)
    return render_template('index.html', posts = posts)

@app.route('/submit', methods=['GET', 'POST'])
def submit():
    if request.method == 'POST':
        post = {"author": request.form['author'], 
        "title": request.form['title'], "text": request.form['text'], "cat":
        request.form['cat']}
        posts = mongo.db.posts
        post_id = posts.insert(post)
        return redirect('/cat/' + str(post_id))
from flask import Flask, jsonify, url_for, redirect, request, render_template
from flask.ext.cors import CORS
from flask_pymongo import PyMongo
from flask_restful import Api, Resource
from bson.json_util import dumps, loads
from datetime import datetime, timedelta

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "scores_db"
CORS(app)
mongo = PyMongo(app, config_prefix='MONGO')

class Score(Resource):
    def get(self, user_id):
        user = mongo.db.users.find_one_or_404({'user_id': user_id})
        return jsonify(mongoToOutput(user))

    def put(self, user_id):
        data = request.get_json()
        if not data:
            return {"response": "no json body",
                    "usage": '{"score":<score>}'}, 400
        score = data.get('score')
        if not score:
            return {"response": "did not include score in request body",
                    "usage": '{"score":<score>}'}, 400

        mongo.db.users.update({'user_id': user_id}, 
                {'$set': {'score': score}, 
                '$max': {'highScore': score}, 
                '$currentDate': {'lastModified': True}}, True)
Beispiel #12
0
console_logger.setFormatter(console_format)
console_logger.setLevel(logging.WARNING)
app.logger.addHandler(console_logger)


if os.environ.get("EXTERNAL"):
    app.config["MONGO_URI"] = os.environ["MONGO_URI"]
    app.config["MONGO_CONNECT"] = False
    app.secret_key = os.environ["random_key"]
    app.config["BROKER_URL"] = os.environ["REDIS_URL"]  # Celery
    app.config["CELERY_RESULT_BACKEND"] = os.environ["REDIS_URL"]
else:
    with open("../Other-Secrets/TITDev.json") as secrets_file:
        secrets = json.load(secrets_file)
    app.config["MONGO_HOST"] = secrets["mongo-host"]
    app.config["MONGO_DBNAME"] = secrets["mongo-db"]
    app.config["MONGO_USERNAME"] = secrets["mongo-user"]
    app.config["MONGO_PASSWORD"] = secrets["mongo-password"]
    app.config["MONGO_PORT"] = secrets["mongo-port"]
    app.config["BROKER_URL"] = secrets["redis-host"]  # Celery
    app.config["CELERY_RESULT_BACKEND"] = secrets["redis-host"]
    app.config["MONGO_CONNECT"] = False
    app.secret_key = secrets["random_key"]

Bootstrap(app)
cdn_theme_url = "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/slate/"
app.extensions['bootstrap']['cdns']["theme"] = WebCDN(cdn_theme_url)  # CDN Theme
app_mongo = PyMongo(app)

# Redis
# read url
Beispiel #13
0
# -*- coding: utf-8 -*-

from flask import Flask
from flask_pymongo import PyMongo

app = Flask("HomeManagementApp")
app.config["MONGO_DBNAME"] = "home_management_db"
app.config["MONGO_CONNECT"] = False
mongo = PyMongo(app)

URL_BASE = '/api/v1/'

# Validation messages for users
SUCCESSFUL_VALIDATION_MESSAGE = "Successful"
USERNAME_NOT_AVAILABLE = "Username field not available"
TOTAL_NOT_AVAILABLE = "Total field not available"
DATE_NOT_AVAILABLE = "Date field not available"
AMOUNT_NOT_AVAILABLE = "Amount field not available"
USER_ALREADY_EXISTS = "User already exists"
Beispiel #14
0
# from flask import Flask
from flask import Flask, jsonify, render_template, request, url_for, redirect, Response, json, send_from_directory
from flask.ext.pymongo import PyMongo
import datetime
from bson.json_util import dumps
from bson.objectid import ObjectId
import os

app = Flask(__name__)
app.config.from_object(__name__)

app.config["MONGO_DBNAME"] = "database_Notes"
# import views
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT, "data/notes/")
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER

ALLOWED_EXTENSIONS = set(["pdf"])


mongo = PyMongo(app, config_prefix="MONGO")


@app.route("/register/", methods=["POST"])
def insertUser():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        fullname = request.form["fullname"]
        email = request.form["email"]
        new_user = {
Beispiel #15
0
from flask import abort
from flask import jsonify
from flask import request
from flask.ext.cors import CORS
from flask.ext.pymongo import PyMongo

from localsettings import DBNAME
from localsettings import HOST
from localsettings import PORT
from localsettings import USERNAME
from localsettings import PASSWORD


app = Flask(__name__)

app.config["MONGO_DBNAME"] = DBNAME
app.config["MONGO_HOST"] = HOST
app.config["MONGO_PORT"] = PORT
app.config["MONGO_USERNAME"] = USERNAME
app.config["MONGO_PASSWORD"] = PASSWORD
mongo = PyMongo(app, config_prefix="MONGO")

CORS(
    app,
    resources={
        r"/contact/*": {"origins": [r".*aomercado\.github\.io", r".*aomercado\.com"]},
        r"/market/*": {"origins": [r".*aomercado\.github\.io", r".*aomercado\.com"]},
    },
)

Beispiel #16
0
from flask import Flask, jsonify
from flask_restful import reqparse, abort, Api, Resource, request
from flask_pymongo import PyMongo 
import os, json, simplejson

cur_dir = '/home/ubuntu/ugradproject/pythonserver/test0'
os.chdir(cur_dir)

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "wifisniff_db"
app.config["MONGO_URI"] = "mongodb://amar:qwerty54321@ds031835.mlab.com:31835/wifisniff_db"
mongo = PyMongo(app, config_prefix="MONGO")
api = Api(app)

parser = reqparse.RequestParser()
parser.add_argument('data')

""" all files """

all_files = {
    "TEXT_FILES": [],
    "JSON_FILES": [],
    "CAP_FILES": [],
    "BASH_FILES": [],
    "PYTHON_FILES": [],
    "ZIP_FILES": []
}

MAP = {"txt": "TEXT_FILES", "json": "JSON_FILES", "cap": "CAP_FILES", "sh": "BASH_FILES", "py": "PYTHON_FILES", "zip": "ZIP_FILES"}

def file_ext(file_name):
Beispiel #17
0
# and view a specific CVE.
#
# Software is free software released under the "Modified BSD license"
#
# Copyright (c) 2013 Alexandre Dulaunoy - a@foo.be

from flask import Flask
from flask import render_template, url_for
from flask.ext.pymongo import PyMongo
import sys

sys.path.append("../lib/")
import cves

app = Flask(__name__, static_folder="static", static_url_path="/static")
app.config["MONGO_DBNAME"] = "cvedb"
mongo = PyMongo(app)


@app.route("/cve/<cveid>")
def cve(cveid):
    cvesp = cves.last(rankinglookup=True, namelookup=True, vfeedlookup=True)
    cve = cvesp.getcve(cveid=cveid)
    if cve is None:
        return page_not_found(404)
    return render_template("cve.html", cve=cve)


@app.route("/")
def last():
    x = mongo.db.cves.find({}).sort("last-modified", -1).limit(50)
Beispiel #18
0
from flask import Flask, jsonify
from flask_pymongo import PyMongo
from flask_restful import Api, Resource
import urllib2
import json

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "moto"
mongo = PyMongo(app, config_prefix='MONGO')
APP_URL = "http://127.0.0.1:5000"

from util import ListConverter

app.url_map.converters['list'] = ListConverter


class Landmarks(Resource):
    def get(self, gps=[], name=None):
        if gps:
            landmark = mongo.db.landmarks.find_one({"location":{"$near":{"$geometry":{
                "type":"Point","coordinates":[float(gps[0]),float(gps[1])]},"$maxDistance":10000000}}})
            url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=1" \
                  "&explaintext&exintro&titles="+'_'.join(landmark['name'].split(' '))+"&redirects=&formatversion=2"
            response = urllib2.urlopen(url)
            data = json.load(response)
            out = None
            extract = data['query']['pages']
            print extract[0]['extract']
            try:
                extract = data['query']['pages'][0]['extract']
                out = extract.split('.')[0::3]
Beispiel #19
0
from flask import Flask
from flask.ext.hopak import Admin
from hopak.ds.mongo import MongoDS
from flask.ext.pymongo import PyMongo
from flaskext.auth import Auth
from flask_bootstrap import Bootstrap

app = Flask(__name__)
app.config["DEFAULT_MAIL_SENDER"] = "neko@ikari.enodev.org"
app.config["MONGO_DBNAME"] = "ikari"
app.secret_key = "aequaiK7coTh1Oepahb7aeNgiaph3OhGIethu9keeeRae1ahieM0tu5oaekeer6S"

Auth(app)
Bootstrap(app)

mongo = PyMongo(app)

admin = Admin(url="/hopak")
admin.init_app(app, MongoDS(mongo))

from flask import Blueprint
from pkg_resources import resource_filename

fg = Blueprint("hopak", __name__, template_folder=resource_filename("hopak", "templates"))
app.register_blueprint(fg)

from flaskext import redtask as task

app.register_blueprint(task.app)
Beispiel #20
0
import requests
import collections
from ipwhois import IPWhois
import pymongo
import whois
import re
import ast
from bson.son import SON

#################
# Configuration #
#################
app = Flask(__name__)
app.config["MONGO_HOST"] = "localhost"
app.config["MONGO_PORT"] = 27017
app.config["MONGO_DBNAME"] = "threatnote"

mongo = PyMongo(app, config_prefix="MONGO")

###################
# Creating routes #
###################


@app.route("/", methods=["GET"])
def home():
    try:
        networks = convert(mongo.db.network.distinct("campaign"))
        dictcount = {}
        dictlist = []
        counts = float(mongo.db.network.count())
Beispiel #21
0
from flask_mail import Mail, Message
from flask.ext.cors import cross_origin
from flask.ext.cache import Cache
from flask.ext.pymongo import PyMongo
# from functools import wraps
import json
import os
import pipes
import phonenumbers
import requests
from datetime import datetime, timedelta
import time
from tempfile import mkdtemp

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "rushapp"
cache_dir = mkdtemp()
cache = Cache(app, config={
    'CACHE_TYPE': 'memcached',
    'CACHE_MEMCACHED_SERVERS': ['127.0.0.1'],
})

app = Flask(__name__)
mongo = PyMongo(app)

import logging.handlers, logging
file_handler = logging.handlers.RotatingFileHandler("/var/www/txirush.log", 'a', 10000000, 1000)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter(
    '%(asctime)s %(levelname)s: %(message)s '
    '[in %(pathname)s:%(lineno)d]'
Beispiel #22
0
# from bs4 import BeautifulSoup
from grab import Grab
from flask import Flask, render_template, redirect, request, url_for
from flask_wtf import Form
from wtforms import StringField
from wtforms.validators import DataRequired, length, regexp
import datetime
from flask_shorturl import ShortUrl
from flask.ext.pymongo import PyMongo
from flask_pymongo import DESCENDING
from flask.ext.qrcode import QRcode
from urllib import parse

app = Flask(__name__)
app.config["SECRET_KEY"] = os.urandom(24)
app.config["MONGO_DBNAME"] = "links"

mongo = PyMongo(app)
su = ShortUrl(app)
QRcode(app)


class MyForm(Form):
    name = StringField(
        "Enter your Long URL",
        validators=[
            DataRequired(message=u"this field is required"),
            length(max=2000, message=u"maximum URL length of 2000 characters"),
            length(min=10, message=u"minimum URL length of 10 characters"),
            regexp(
                r"(https?://|ftp://)",
Beispiel #23
0
from flask import Flask, render_template, request, redirect, abort, jsonify
from flask.ext.pymongo import PyMongo
from ast import literal_eval
import json
import pymongo
from bson.json_util import dumps
import hashlib

#end authentication
app = Flask(__name__)
app.config["MONGO_DBNAME"] = "habigotchi"
app.config["MONGO_HOST"] = "oceanic.mongohq.com"
app.config["MONGO_PORT"] = 10008
app.config["MONGO_USERNAME"] = "admin"
app.config["MONGO_PASSWORD"] = "1234"
app.debug= True
mongo = PyMongo(app)

m = hashlib.sha256

def authenticate(user, pw):
    users = mongo.db.users
    hashed = m(user+pw).hexdigest()
    return users.find_one({"password": hashed}) != None

@app.route('/', methods=['GET', 'POST'])
def landing():
    if request.method == 'POST':
        users = mongo.db.users
        check = users.find_one({"name":request.form['name']})
        if check != None:
Beispiel #24
0
import config
from flask import Flask
from flask.ext.pymongo import PyMongo

myapp = Flask(__name__,static_folder='../public/static')
myapp.config["MONGO_HOST"] = config.MONGO_HOST
myapp.config["MONGO_PORT"] = config.MONGO_PORT
myapp.config["MONGO_DBNAME"] = config.MONGO_DBNAME
myapp.config["MONGO_USERNAME"] = config.MONGO_USERNAME
myapp.config["MONGO_PASSWORD"] = config.MONGO_PASSWORD
mongo = PyMongo(myapp)

import views
# -*- coding: utf-8 -*-

from flask import Flask, jsonify, url_for, redirect, request
from flask_pymongo import PyMongo
from flask_restful import Api, Resource
from datetime import datetime

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "iot_db"
mongo = PyMongo(app, config_prefix='MONGO')

class Devices(Resource):
    def get(self, device_key=None):
        data = []

        if device_key:
            cursor = mongo.db.device.find({"device_key": device_key}, {"_id": 0}).limit(10)
            for device in cursor:
                data.append(device)

            return jsonify({"device": device_key, "response": data})

        else:
            cursor = mongo.db.device.find({}, {"_id": 0, "update_time": 0}).limit(10)

            for device in cursor:
                print device
                data.append(device)

            return jsonify({"response": data})
Beispiel #26
0
from flask import Flask, jsonify, request, make_response,redirect,url_for
from flask_restful import reqparse, abort, Api, Resource
from flask_pymongo import PyMongo
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
from itsdangerous import (TimedJSONWebSignatureSerializer
                          as Serializer, BadSignature, SignatureExpired)

UPLOAD_FOLDER = 'file-uploads'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "property"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SECRET_KEY'] = 'this is a property app'
mongo = PyMongo(app)
api = Api(app)
auth = HTTPBasicAuth()
authT = HTTPTokenAuth(scheme='Token')


APP_URL = "http://127.0.0.1:5000"

USERS = {
  'user1': {
    'username': 'user1',
    'password': '123',
    'img': 'build an API'
  },
  'user2': {
    'username': 'user2',
    'password': '123',
Beispiel #27
0
from flask import Flask
#from flask.ext.pymongo import PyMongo
app=Flask(__name__)


from views import *
"""
from pymongo import MongoClient



client = MongoClient("colab-sbx-280.oit.duke.edu", "27017")
db = client.hackmit
"""



app.config["MONGO_HOST"] = "mongodb://colab-sbx-280.oit.duke.edu:27107"
app.config["MONGO_PORT"] = 27017
app.config["MONGO_DBNAME"] = "hackmit"
mongo = PyMongo(app)



#not sure what this line does, will ignore for now.. O:)
#app.config.from_object(__name__)

app.run()

# -*- coding: utf-8 -*-

from flask import Flask, jsonify, url_for, redirect, request
from flask_pymongo import PyMongo
from flask_restful import Api, Resource

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "students_db"
mongo = PyMongo(app, config_prefix='MONGO')
APP_URL = "http://127.0.0.1:5000"


class Student(Resource):
    def get(self, registration=None, department=None):
        data = []

        if registration:
            studnet_info = mongo.db.student.find_one({"registration": registration}, {"_id": 0})
            if studnet_info:
                return jsonify({"status": "ok", "data": studnet_info})
            else:
                return {"response": "no student found for {}".format(registration)}

        elif department:
            cursor = mongo.db.student.find({"department": department}, {"_id": 0}).limit(10)
            for student in cursor:
                student['url'] = APP_URL + url_for('students') + "/" + student.get('registration')
                data.append(student)

            return jsonify({"department": department, "response": data})