Esempio n. 1
0
def info() -> Tuple[str, Optional[int]]:
    if not flask_login.current_user.is_teacher():
        return '403 Forbidden.', 403

    if request.method == 'POST':
        user = flask_login.current_user
        status = ''
        messages = []
        url = ''

        try:
            if request.form['password'] != request.form['re_password']:
                messages.append(('密碼不符', 'danger'))

            if not validate_email(request.form['email']):
                messages.append(('email 格式不符', 'danger'))

            if not request.form['phone1'] or not request.form['phone2']:
                messages.append(('請輸入學校聯絡電話', 'danger'))

            if any(not digit.isdigit() for digit in request.form['phone1'] + request.form['phone2'] + request.form['phone3'] + request.form['cellphone']):
                messages.append(('電話號碼不可包含非數字', 'danger'))

            if 'school' not in request.form or not request.form['school']:
                messages.append(('請選擇學校', 'danger'))

            if messages:
                raise ValueError

            if request.form['password']:
                user.password = hash_password(request.form['password'])
            user.email = request.form['email']
            user.work_phone = '%s.%s.%s' % (
                request.form['phone1'], request.form['phone2'], request.form['phone3'])
            user.cell_phone = request.form['cellphone']
            user.school_id = request.form['school']
        except ValueError:
            status = 'error'
        else:
            get_db_session().commit()
            status = 'ok'
            flash('更新成功', 'success')
            url = url_for('user_mod.info')
        return jsonify(status=status, messages=messages, url=url)

    return render_template(
        'user_info.html',
        current_user=flask_login.current_user
    )
Esempio n. 2
0
    def on_list_select(self, evt):
        """
        Actions to be triggered when a user clicks an item in the listbox.

        Defined above in create_gui(), where on_list_select is bound to the
        listbox selection.

        Parameters (apart from self):
            evt: object containing information about the mouse click

        Return: None
        """

        w = evt.widget
        index = int(w.curselection()[0])
        value = w.get(index)

        print(index)
        print(value)

        session = db.get_db_session()
        result = self.salesperson_dao.find_by_id(session, value)
        session.close()

        print("result: ", result)

        sp = result['salesperson']
        self.populate_fields(sp)

        pass
Esempio n. 3
0
	def generate(self, uri, paginate_until=None, after=None):
		method = 'GET'
		response_data = []
		url = self._base_url + uri
		response = requests.request(
			method = method,
			url = url,
			params = {'after': after},
			auth = self._auth,
			verify = True)
		print(response)
		print(response.text)
		if isinstance(response.json(), list):
			response_data += response.json()
		else:
			yield response.json()
		if paginate_until is None:
			for r in response_data:
				yield r
		else:
			db_session = get_db_session()
			pagination_key = paginate_until['key']
			pagination_condition = paginate_until['condition']
			if len(response_data) == 0:
				return
			for r in response_data:
				if pagination_condition(r[pagination_key]):
					yield r
			while pagination_condition(response_data[-1][pagination_key]):
				if 'CB-AFTER' in response.headers:
					time.sleep(0.25) # To avoid rate limit
					after = response.headers['CB-AFTER']
					response = requests.request(
						method=method, url=url, auth=self._auth, params={'after': after})
					response_data = response.json()
					if not isinstance(response_data, list):
						response_data = [response_data]
					if len(response_data) == 0:
						break
					for r in response_data:
						if pagination_condition(r[pagination_key]):
							yield r
					try:
						# Record pagination info in DB
						pagination = Pagination(
							account = get_account_from_base_url(self._base_url),
							product_id = get_product_id_from_uri(uri),
							url = url,
							start_time = response_data[-1]['created_at'],
							end_time = response_data[0]['created_at'],
							cursor_before = response.headers['CB-BEFORE'],
							cursor_after = response.headers['CB-AFTER'])
						db_session.add(pagination)
						db_session.commit()
					except Exception as e:
						print(str(e))
						# Let this go since it's just extra info that is nice to have
				else:
					break
			db_session.remove()
Esempio n. 4
0
def show_party(party_subdomain):
    db_session = get_db_session()
    party = db_session.query(Orgy).filter(Orgy.name.ilike(party_subdomain)).filter(Orgy.is_old == False).one_or_none()
    if not party:
        return 'Party not found! Make one <a href="//my.corgiorgy.com">here</a>!', 404
    else:
        return render_template("party.html", party=party)
Esempio n. 5
0
def delete_party():
    requestor_ip = request.remote_addr
    delete_token = request.args.get('delete_token')
    name = request.args.get('name')

    if (not name) or (not delete_token) or (not requestor_ip): 
        return 'Invalid request'

    db_session = get_db_session()
    party_to_delete = db_session.query(Orgy).filter(Orgy.name == name)\
                                            .one_or_none()
    if not party_to_delete:
        return 'Invalid request'

    if (not party_to_delete.creator_ip) or (party_to_delete.creator_ip == '127.0.0.1/32'):
        return 'Invalid request'
    else:
        creator_ip = party_to_delete.creator_ip.replace('/32','')

    # Additional sanity check
    if creator_ip != requestor_ip:
        return 'Invalid request'
    
    token_message = creator_ip + party_to_delete.name
    valid_delete_token = hmac.new(mycorgi_app.mycorgi_app.config['SECRET_DELETE_KEY'], token_message, hashlib.sha1).hexdigest()

    if delete_token == valid_delete_token:
        db_session.delete(party_to_delete)
        db_session.commit()
        print 'deleted party', party_to_delete.name
        return 'Party deleted! Make another one <a href="//my.corgiorgy.com">here</a>!'
    else:
        return 'Invalid request!'
Esempio n. 6
0
 def __init__(self):
     self.session, self.engine = get_db_session()
     self.workflows = WorkflowClient(self.session)
     self.tasks = TaskClient(self.session)
     self.minions = MinionClient(self.session)
     self.users = UserClient(self.session)
     self.tenants = TenantClient(self.session)
Esempio n. 7
0
    def process_request(self, message):
        if 'text' not in message:
            return None

        self.session = database.get_db_session()()

        message_text = message['text']
        chat_id = message['chat']['id']

        message_list = message_text.split()
        if message_list[0].startswith('/'):
            command_name = message_list[0][1:]
            command = self._find_command(command_name)
            args = message_list[1:]
            if command:
                return_message = command(chat_id, args)
            else:
                return None
        else:
            return_message = self.default_command(chat_id, [])

        response = {
            'chat_id': chat_id,
            'text': return_message,
            'parse_mode': 'markdown',
        }

        self.session.close()

        return response
Esempio n. 8
0
    def delete(self):
        """
        Delete a record from the database
        The vehicle_id of the record to be deleted is obtained from a 
        global attribute.

        A messagebox is used display the outcome (success or failure) 
        of the delete operation to the user.

        Parameters (apart from self): None
 
        Return: None

        """

        # Grab the vehicle_id from the stringvar
        id = self.vehicle_id.get()
        print(id)

        # Call the data access object to do the job
        # Pass the id as parameter to the delete() method
        session = db.get_db_session()  # Get a session (database.py)
        result = self.vhc_dao.delete(session, id)
        session.close()  # Close the session

        # Display the returned message to the user - use a messagebox
        # Display everything that is returned in the result
        messagebox.showinfo(self.mb_title_bar, result)
        pass
Esempio n. 9
0
    def create(self, data):
        """
        Create a new record in the database.
        A messagebox is used display the outcome (success or failure) 
        of the create operation to the user.

        Parameters (apart from self):
            data: dictionary object containing vehicle data to be saved
 
        Return: None
        """

        print("Creating a vehicle ...")
        print(data)

        session = db.get_db_session()  # Get a session (database.py)
        result = self.vhc_dao.create(session, data)
        # result is a tuple e.g. ("vehicle added successfully", 1004)
        #result, vehicle_id = self.vhc.create(data)
        # if you wish to get the message and vehicle_id separately
        session.close()  # Close the session

        # Display the returned message to the user - use a messagebox
        # For 'tkinter messagebox' options,
        # refer to http://effbot.org/tkinterbook/tkinter-standard-dialogs.htm
        # Format: message.function(title, message [, options])
        # Functions: showinfo, showwarning, showerror, askquestion,
        #            askokcancel, askyesno, or askretrycancel
        # Use the icon= option to specify which icon to display
        # e.g. icon="warning", "error", "info", "question"
        # Display everything that is returned in the result
        messagebox.showinfo(self.mb_title_bar, result)

        pass
Esempio n. 10
0
    def on_list_select(self, evt):
        """
        on_list_select() is triggered when a user clicks an item in the listbox.
        This was defined with the statement 
        "self.lb_ids.bind('<<ListboxSelect>>', self.on_list_select)" 
        defined above in create_gui()

        Parameters (apart from self):
            evt: object containing information about the mouse click

        Return: None
        """
        # For more information on 'tkinter events',
        # refer to http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
        w = evt.widget
        index = int(w.curselection()[0])
        # index = position of the item clicked in the list, first item is item 0 not 1
        value = w.get(index)
        # value of the item clicked, in our case it's the vehicle_id
        print(index)
        print(value)

        # Call find_by_id and populate the stringvars of the form
        session = db.get_db_session()  # Get a session (database.py)
        result = self.vhc_dao.find_by_id(session, value)
        session.close()  # close the session
        print("result", result)
        # { "vehicle" : {"vehicle_id": "", "vehicle_make": "", etc}}
        vhc = result['vehicle']
        self.populate_fields(vhc)
        pass
Esempio n. 11
0
    def load(self):
        """
        Retrieve a list of IDs from the database and load them into a listbox
 
        Parameters (apart from self):
  
        Return: None
        """

        session = db.get_db_session()  # Get a session (database.py)
        result = self.vhc_dao.find_ids(session)  # {"vehicle_ids": [1, 2, 3]}
        session.close()  # Close the session
        print("result", result)
        # Check if there is an entry in the result dictionary
        if "vehicle_ids" in result:
            list_ids = result[
                'vehicle_ids']  # will crash if there is no entry!
            # Set the returned list into the listbox
            # Before doing that, must clear any previous list in the box
            self.lb_ids.delete(0, tk.END)
            print("Setting vehicle_id in listbox ...")
            for x in list_ids:
                self.lb_ids.insert(tk.END, x)
                #print(x)
            pass
Esempio n. 12
0
def get_user(id):
  s = get_db_session()
  try:
    user = s.query(User).filter_by(id=id).one()
    return Response(json.dumps(user.to_dict()), status=200, mimetype='application/json')
  except NoResultFound:
    return Response("User does not exist", 404)
Esempio n. 13
0
    def delete(self):
        """
        Delete a record from the database.

        The salesperson_id of the record to be deleted is obtained from a 
        global attribute.

        A messagebox is used display the outcome (success or failure) 
        of the delete operation to the user.

        Parameters (apart from self): None
 
        Return: None

        """
        print("Deleting a salesperson ...")

        sp_id = self.salesperson_id.get()
        print(id)

        session = db.get_db_session()
        result = self.salesperson_dao.delete(session, sp_id)
        session.close()

        messagebox.showinfo(self.mb_title_bar, result)
        pass
Esempio n. 14
0
def register() -> str:
    if request.method == 'POST':
        status = ''
        messages = []
        url = ''

        try:
            if not request.form['name']:
                messages.append(('請輸入姓名', 'danger'))
            elif any(char.isdigit() for char in request.form['name']):
                messages.append(('姓名不可包含數字', 'danger'))

            if not request.form['username']:
                messages.append(('請輸入使用者帳號', 'danger'))

            if not request.form['password']:
                messages.append(('請輸入密碼', 'danger'))
            elif request.form['password'] != request.form['re_password']:
                messages.append(('密碼不符', 'danger'))

            if not validate_email(request.form['email']):
                messages.append(('email 格式不符', 'danger'))

            if not request.form['phone1'] or not request.form['phone2']:
                messages.append(('請輸入學校聯絡電話', 'danger'))

            if any(not digit.isdigit() for digit in request.form['phone1'] + request.form['phone2'] + request.form['phone3'] + request.form['cellphone']):
                messages.append(('電話號碼不可包含非數字', 'danger'))

            if 'school' not in request.form or not request.form['school']:
                messages.append(('請選擇學校', 'danger'))

            if messages:
                raise ValueError

            user = User(request.form['username'], request.form['email'])
            user.realname = request.form['name']
            user.password = hash_password(request.form['password'])
            user.work_phone = '%s.%s.%s' % (
                request.form['phone1'], request.form['phone2'], request.form['phone3'])
            user.cell_phone = request.form['cellphone']
            user.school_id = request.form['school']
            user.create_time = datetime.datetime.now()
            user.type = 'teacher'
        except ValueError:
            status = 'error'
        else:
            db_session = get_db_session()
            db_session.add(user)
            db_session.commit()
            status = 'ok'
            flash('註冊成功', 'success')
            url = url_for('user_mod.login')
        return jsonify(status=status, messages=messages, url=url)
    return render_template(
        'user_register.html',
        current_user=flask_login.current_user
    )
Esempio n. 15
0
 def store_in_db(self) -> None:
     """Store data into database
     """
     with get_db_session() as db_session:
         channels, shows = self.get_tv_metadata(db_session)
         complete_result = self.clean_data(db_session, channels)
         self.parse_to_schema(db_session, shows, complete_result)
         db_session.commit()
         print('Successfully store data into database....')
Esempio n. 16
0
def delete_products(args, location="form"):
  ids = args["ids"]
  s = get_db_session()
  try:
    s.query(Product).filter(Product.id.in_(ids)).delete()
    s.commit()
    return Response('Products deleted', 200)
  except NoResultFound:
    return Response("Products do not exist", 404)
def get_transaction(id):
    s = get_db_session()
    try:
        transaction = s.query(Transaction).filter_by(id=id).one()
        return Response(json.dumps(transaction.to_dict()),
                        status=200,
                        mimetype='application/json')
    except NoResultFound:
        return Response("transaction does not exist", 404)
def delete_transaction(id):
    s = get_db_session()
    try:
        transaction = s.query(Transaction).filter_by(id=id).one()
        s.delete(transaction)
        s.commit()
        return Response('transaction deleted', 200)
    except NoResultFound:
        return Response("transaction does not exist", 404)
def get_transactions_by_user(id):
    s = get_db_session()
    try:
        transactions = s.query(Transaction).filter_by(user_id=id)
        return Response(json.dumps([u.to_dict() for u in transactions]),
                        status=200,
                        mimetype='application/json')
    except NoResultFound:
        return Response("transactions do not exist", 404)
Esempio n. 20
0
def show_old_party(old_party_name):
    db_session = get_db_session()
    party = db_session.query(Orgy)\
                      .filter(Orgy.name == old_party_name)\
                      .filter(Orgy.is_old == True)\
                      .one_or_none()
    if not party:
        return 'Party not found! Make one <a href="//my.corgiorgy.com">here</a>!', 404
    else:
        return render_template('party.html', party=party)
Esempio n. 21
0
def create_product(args, location="form"):
  name = args["name"]
  description = args["description"]
  imageSrc = args["imageSrc"]
  price = args["price"]
  product = Product(name, description, imageSrc, price)
  s = get_db_session()
  s.add(product)
  s.commit()
  return Response('Product created', 201)
Esempio n. 22
0
    def update(self, data):

        print("Updating a customer ...")
        print(data)

        session = db.get_db_session() # Get a session (database.py)
        result = self.customer_dao.update(session, data['customer_id'], data)
        session.close() # close the session
   
        messagebox.showinfo(self.mb_title_bar, result)
        pass
Esempio n. 23
0
 def store_data(self, movie_data):
     """Store data into database."""
     with get_db_session() as db_session:
         product_data = [
             ProductSchema(product_id=str(uuid.uuid4())[:10],
                           store_pcs=len(data.get('product_name')),
                           price=int(float(data.get('movie_score'))) *
                           10 if data.get('movie_score') else 0,
                           **data) for data in movie_data
         ]
         product.add_all(db_session, product_data)
         db_session.commit()
Esempio n. 24
0
def create_user(args, location="form"):
  username = args["username"]
  password = args["password"]
  email = args["email"]
  firstname = args["firstname"]
  lastname = args["lastname"]
  role = "user"
  user = User(username, password, email, firstname, lastname, role)
  s = get_db_session()
  s.add(user)
  s.commit()
  return Response('User created', 201)
Esempio n. 25
0
	def get_fills(self, backwards_until, afters):
		db_session = get_db_session()
		try:
			for product_id, after in afters.items():
				self._log.info('Ingesting fills for product "%s"' %(product_id))
				for fill in self._api.get_fills(product_id, backwards_until, after):
					self.upsert_fill(fill, db_session)
		except Exception as e:
			db_session.rollback()
			raise e
		finally:
			db_session.close()
Esempio n. 26
0
    def create(self, data):
        
        print("Creating an customer ...")
        print(data)

        session = db.get_db_session() # Get a session
        result = self.customer_dao.create(session, data)
        session.close() # Close the session

        messagebox.showinfo(self.mb_title_bar, result)

        pass
Esempio n. 27
0
   def delete(self):
       
       # Grab the customer_id from the stringvar
       id = self.customer_id.get() 
       print(id)
       
       session = db.get_db_session() # Get a session (database.py)
       result = self.customer_dao.delete(session, id)
       session.close() # Close the session
 
       messagebox.showinfo(self.mb_title_bar, result)
       pass
Esempio n. 28
0
 def add_transactions(self):
     import csv
     db_session = get_db_session()
     try:
         with open(self._filepath, 'r') as csvfile:
             reader = csv.DictReader(csvfile)
             for i, row in enumerate(reader):
                 self.upsert_transaction(row, db_session)
     except Exception as e:
         db_session.rollback()
         raise e
     finally:
         db_session.close()
Esempio n. 29
0
 def load(self):
     session = db.get_db_session() # Get a session (database.py)
     result = self.flt_dao.find_ids(session) # {"employee_ids": [1, 2, 3]}
     session.close() # Close the session
     print("result", result)
     # Check if there is an entry in the result dictionary
     if "flight_ids" in result: 
         list_ids = result['flight_ids'] 
         self.lb_ids.delete(0,tk.END)
         print("Setting flight_id in listbox ...")
         for x in list_ids:
             self.lb_ids.insert(tk.END, x)
             #print(x)
         pass
Esempio n. 30
0
def get_single_visit_by_id(visit_id):
    """
    Function gets a visit id by key
    :param visit_id: Input param that represents the user_id
    :return: Success: Response with json output with the requested format
    """
    request_id = uuid.uuid4()
    try:
        log.info("[{}] User visits requested for visit ID: {}".format(
            request_id, visit_id))
        return jsonify(
            get_visit_by_id_helper(get_db_session(), request_id, visit_id))
    except Invalid as e:
        log.warning(" Malformed input: {}".format(str(e)))
        return Response(ExceptionMessage.BAD_REQUEST, status=406)
Esempio n. 31
0
def show_party(party_subdomain):
    db_session = get_db_session()
    party = db_session.query(Orgy)\
                      .filter(Orgy.name.ilike(party_subdomain))\
                      .filter(Orgy.is_old == False)\
                      .one_or_none()
    if not party:
        return 'Party not found! Make one <a href="//my.corgiorgy.com">here</a>!', 404
    
    if party.creator_ip:
        creator_ip = party.creator_ip.replace('/32','')
        if creator_ip == request.remote_addr:
            token_message = creator_ip + party.name  
            delete_token = hmac.new(mycorgi_app.mycorgi_app.config['SECRET_DELETE_KEY'], token_message, hashlib.sha1).hexdigest()
            delete_url = '?name='+party.name+'&delete_token='+delete_token
        else:
            delete_url = None
    return render_template('party.html', party=party, delete_url=delete_url)
Esempio n. 32
0
def check_name():
    name = request.form.get('name')
    if not name:
        return 'InvalidName'
    elif not re.search("^[a-zA-Z0-9\-]+$", name):
        return 'InvalidName'
    elif not len(name) < 64:
        return 'InvalidName'
    else:
        db_session = get_db_session()
        existing_party = db_session.query(Orgy)\
                                    .filter(Orgy.name.ilike(name))\
                                    .filter(Orgy.is_old == False)\
                                    .one_or_none()
        if existing_party:
            return 'InUse'
        else:
            return 'Success'
Esempio n. 33
0
#coding: utf-8

import tornado.web
import os
from urls import handlers
from templates import get_template_lookup
from database import get_db_session

settings = {

    'template_lookup': get_template_lookup(),

    'template_path': os.path.join(os.path.dirname(__file__), 'template'),
    'static_path': os.path.join(os.path.dirname(__file__), 'static'),
    'debug': True,
    "login_url": "/auth/signin",
    'cookie_secret': 'Ku8JJ9hL9Shj=',
    "xsrf_cookies": True,
    'dbsession': get_db_session()

}

application = tornado.web.Application( handlers, **settings )
Esempio n. 34
0
def create_party():
    # Required fields 
    name = request.form.get('name')
    foreground = request.form.get('foreground')
    background = request.form.get('background')
    direction = request.form.get('direction')
    # Optional fields
    youtube_url = request.form.get('youtube')
    creator_ip = request.remote_addr

    # Make sure foreground was included in POST
    if not foreground:
        return 'Missing foreground! Please upload a foreground image', 400
    # Validate image foreground image input and construct imgur URL
    if re.search(r"^[a-zA-Z0-9]+$", foreground):
        foreground_url = "http://i.imgur.com/" + foreground + ".gif"
    else:
        return 'Foreground image invalid! Please retry upload', 400 

    # Make sure background was included in POST 
    if not background:        
        return 'Missing background! Please upload a background image', 400 
    # Validate image background image input and construct imgur URL
    if re.search("^[a-zA-Z0-9]+$", background):
        background_url = "http://i.imgur.com/" + background + ".gif"
    else:
        return 'Background image invalid! Please retry upload', 400 

    # Make sure direction was included in POST
    if not direction:
        return 'Missing direction! Hey wat r u doin?', 400
    # Validate direction input and construct ltr/rtl boolean
    if direction == 'right':
        is_left_to_right = True
    elif direction == 'left':
        is_left_to_right = False
    else:
        return 'Invalid direction! Hey wat r u doing?', 400

    # Validate youtube URL
    if youtube_url:
        youtube_match = re.search(YOUTUBE_REGEX, youtube_url)
        if youtube_match:
            youtube_id = youtube_match.group(6) 
        else:
            return 'Invalid YouTube URL!', 400
    else:
        youtube_id = None

    # Make sure name was included in POST
    if not name:
        return 'Missing name! Please pick a name for your party', 400
    # Validate name
    elif not re.search("^[a-zA-Z0-9\-]+$", name):
        return 'Invalid name! Pick a different name', 400
    # Make sure name isn't too long to be a subdomain
    elif len(name) > 63:
        return 'Name too long! Pick a shorter name', 400
    # Forbid protected subdomains
    elif name.lower() in ['my', 'static', 'api', 'www']:
        return 'Forbidden name! Pick a different name', 400

    # Create DB session
    db_session = get_db_session()

    # Make sure name is not already taken
    existing_orgy = db_session.query(Orgy)\
                               .filter(Orgy.name.ilike(name))\
                               .filter(Orgy.is_old == False)\
                               .one_or_none()
    if existing_orgy:
        return name + ' already exists! Pick a different name', 400

    # Instantiate new party and commit to DB
    new_orgy = Orgy(name=name, is_old=False,
                    foreground_url=foreground_url,
                    background_url=background_url,
                    is_left_to_right=is_left_to_right, 
                    youtube_id=youtube_id, creator_ip=creator_ip)

    db_session.add(new_orgy)
    db_session.commit()
    # Return new party URL for client-side redirect target
    new_party_url = 'http://' + name.lower() + '.corgiorgy.com'
    print name, 'party:', new_party_url
    return new_party_url, 201