Esempio n. 1
0
 def cult():
     if request.method == "GET":
         return render("index.html")
     elif request.method == "POST":
         soup = get_site_file("bitcoin")
         context = soup.find_all('h1')
         return render("index.html", context={context})
Esempio n. 2
0
def inventory():
    init_database()
    msg = None
    products = None
    db = sqlite3.connect(DATABASE_NAME)
    cursor = db.cursor()
    if request.method == 'POST':
        search = request.form['Material_id']
        try:
            querry = "SELECT * FROM products WHERE Material LIKE '{}%' ORDER BY Material".format(
                search)
            cursor.execute(querry)
            products = cursor.fetchall()
        except sqlite3.Error as e:
            msg = f"An error occurred: {e.args[0]}"
        if msg:
            print(msg)
        return render('search.html',
                      form=search,
                      link=link,
                      title="inventory",
                      products=products)
    return render('search.html',
                  link=link,
                  title="Search History",
                  products=products)
Esempio n. 3
0
def search(request):
    if request.method == 'POST':
        word = request.form.get('keyword')
        videos = get_videos(word)
        return render('result.html', word=word, videos=videos)

    return render('index.html')
Esempio n. 4
0
def videoGallery():
    try:
        if session['email']:
            cur = conn.cursor()
            sql = 'SELECT videos_name,videos_date,videos_timeStart,videos_timeEnd FROM videos_member WHERE member_email = %s'
            cur.execute(sql, (session['email']))
            rows = cur.fetchall()
            cur.close()

            name_list = []  # สร้าง list เก็บข้อมูล ชื่อวิดิโอ ที่ SELECT ออกมา
            date_list = []  # สร้าง list เก็บข้อมูล วันวิดิโอ ที่ SELECT ออกมา
            for row in rows:
                name_list.append(row[0])  # row[0] = ข้อมูล ชื่อ
                date_list.append(row[1])  # row[1] = ข้อมูล วัน

            # ลบ ข้อมูลที่ซ้ำกันใน List
            name_list = list(dict.fromkeys(name_list))
            date_list = list(dict.fromkeys(date_list))

            # ลบไฟล์ที่เกิดจากบัค
            file_names = glob.glob1(
                os.path.join('static', session['email'], 'Video'), '*')
            for file_name in file_names:
                if file_name in name_list:
                    pass
                else:
                    os.remove(
                        os.path.join(os.getcwd(), 'static', session['email'],
                                     "Video", file_name))

            return render('video_gallery.html',
                          dates=date_list,
                          video_datas=rows)
    except:
        return render('login.html')
Esempio n. 5
0
def product_upload():
    init_database()
    msg = None
    db = sqlite3.connect(DATABASE_NAME)
    cursor = db.cursor()

    cursor.execute("SELECT * FROM products")
    products = cursor.fetchall()

    if request.method == 'POST':
        try:
            if request.files:
                # On upload I am Dropping Table and Recreating new one to remove duplicates
                cursor.execute("""
                    DROP TABLE IF EXISTS products
                    """)
                cursor.execute("""
                    CREATE TABLE IF NOT EXISTS products(Material INTEGER PRIMARY KEY,
                                    Material_Description TEXT,
                                    MTyp TEXT,
                                    Typ TEXT,
                                    Division TEXT,
                                    ABC TEXT,
                                    Reorder_Pt TEXT,
                                    Max_Level TEXT,
                                    Total_Stock TEXT,
                                    loc_name TEXT);
                    """)
                file = request.files["filename"]
                file.save(os.path.join(ROOT_PATH, file.filename))
                df = pd.read_excel(os.path.join(ROOT_PATH, file.filename))
                df.to_sql('products',
                          con=db,
                          if_exists='append',
                          index=False,
                          chunksize=100)
                try:
                    os.remove(os.path.join(ROOT_PATH, file.filename))
                    print("% s removed successfully" %
                          os.path.join(ROOT_PATH, file.filename))
                except OSError as error:
                    print(error)
                    print("File path can not be removed")

                cursor.execute("SELECT * FROM products")
                products = cursor.fetchall()
                return render('upload.html',
                              link=link,
                              products=products,
                              title="Inventory Summary")
        except Exception as e:
            msg = f"An error occurred: {e}"
        if msg:
            print(msg)

    return render('upload.html',
                  link=link,
                  products=products,
                  transaction_message=msg,
                  title="Product Inventory")
Esempio n. 6
0
def Ppage():
    if request.method == "POST":
        print(request.form)
        '''
        USE your model logic to write it to database
        '''
        return render('SuccessPage.html')
    else:
        return render('form.html')
Esempio n. 7
0
def board_triky(n):
    ch = 'x'
    if board[-1]:
        ch = 'o'
    board[n][0] = ch
    board[n][1] = 'disabled'
    for i in range(9):
        if board[i][0] == 'b':
            board[i][0] = ''
    Game.is_winner(board)
    # YELLOW EN CASO DE EMPATE; ROJO SI GANA MAQUINA; VERDE SI GANA USUARIO
    if Game.is_winner(board)[0]:  # and (Game.is_winner(board)[1] != 'yellow'):

        new_board_format = Game.to_format_JSON_LEARN(board,
                                                     Game.is_winner(board)[1])
        print(new_board_format)
        print(Game.learn_new_play(new_board_format, Game.is_winner(board)[1]))
        for i in range(9):
            if board[i][0] == 'b':
                board[i][0] = ''
        flash("Congratulations, You Win!")
        return render('index.html', board=board)
    else:
        new_board_format = Game.to_format_JSON(board)

        if 'b' in new_board_format['state_current_play']:

            machine_of_play = Game.playMachine(new_board_format)
            board[int(machine_of_play)][0] = 'x'
            board[int(machine_of_play)][1] = 'disabled'

        if Game.is_winner(board)[0]:
            new_board_format = Game.to_format_JSON_LEARN(
                board,
                Game.is_winner(board)[1])
            print(new_board_format)
            print(
                Game.learn_new_play(new_board_format,
                                    Game.is_winner(board)[1]))
            for i in range(9):
                if board[i][0] == 'b':
                    board[i][0] = ''
            flash("I'm Sorry,You Lost! ")
            return render('index.html', board=board)
        else:
            Tied = True
            for i in range(9):
                if board[i][0] == 'b':
                    Tied = False
                    board[i][0] = ''
            if Tied:
                flash("Tied Game! ")
                return render('index.html', board=board)
            else:
                flash("Keep playing! ")
                return render('index.html', board=board)
Esempio n. 8
0
def login():
   if request.method == "POST":
      if request.form["username"] == "admin" and request.form["password"] == "wifination":
         response = redirect(url_for('showAdmin'))
         response.set_cookie('jklol',value='keox')
         return response
      else:
         return render("admin-login.html",page_vars={'fail':True})
   else:
      return render("admin-login.html",page_vars={})
Esempio n. 9
0
def remove_profile():
    """
    Remove user profile

    :return mix:
    """

    # get uid
    uid = int(session['uid'])

    # get user items
    items = [item.serialize for item in get_items_by_user(uid)]

    # if the user have any items create message
    if len(items) > 0:
        flash('First remove your cars', 'error')

    # get user
    user = get_user_by_id(uid)

    # get user full name
    name = ' '.join([user.first_name, user.last_name])

    if request.method == 'POST' and request.form['csrf_token'] == csrf_token:

        if len(items) > 0:
            return render('users/delete_profile.html',
                          brands=brands,
                          csrf_token=csrf_token)

        # get absolute path to image
        path = ''.join([BASE_DIR, user.picture])

        # if file exist remove the image file
        if os.path.isfile(path):
            os.unlink(path)

        # remove user data from database
        remove_user(uid)

        # remove session
        del session['uid']

        if 'provider' in session:
            del session['provider']

        # create success message
        flash('Profile "%s" was removed' % name, 'success')

        # redirect user to home page
        return redirect('/', 302)

    return render('users/delete_profile.html',
                  brands=brands,
                  csrf_token=csrf_token)
Esempio n. 10
0
def camera():
    try:
        if session['email']:
            alert_delay = get_delay(session['email'])[0]
            record_delay = get_delay(session['email'])[1]

            return render(
                'camera.html', alert=alert_delay,
                record=record_delay)  # แสดงค่าการตั้งค่ากล้อง ของ ผู้ใช้
    except:
        return render('login.html')
Esempio n. 11
0
def registro():
    if request.method == 'POST':
        fullname = request.form['fullname']
        username = request.form['username']
        password = request.form['password']
        confirm_password = request.form['confirm_password']

        if password == confirm_password:
            USERS[username] = {'fullname': fullname, 'password': password}
            return render('registro.html', success=True)

    return render('registro.html', success=False)
Esempio n. 12
0
def index():
    data = request.args.to_dict()

    for form in forms:
        data[form] = data[form] if form in data else None

    styles = data['styles'] = data['styles'] if 'styles' in data else '/static/style.css'

    if not data['name']:
        return render('create.html', styles=styles)

    return render('index.html', data=data, styles=styles)
Esempio n. 13
0
def index(**kwargs):
    if request.args.get("submit") is not None:
        return redirect(url_for(".index", **get_params(["title", "oldid"])), code=c.REQUEST)

    normalize(["title"], kwargs)
    form = dykchecker.form.getForm()(request.form, **kwargs)
    data = dykchecker.model.Model(form=form)
    if form.validate(data):
        data.render()
        return render("page.html", tool=__name__, form=form, data=data)

    else:
        return render("index.html", tool=__name__, form=form)
Esempio n. 14
0
def index():
    if request.method == 'POST':
        try:
            result = createResponse(request.form['search'])
            if result:
                return render('content.html', result=result)
            else:
                return render('404.html')
        except:
            # empty
            return render('404.html')
    else:
        images = getImageLinks()
        return render('index.html', images=images)
Esempio n. 15
0
def edit_car(item_id):
    """
    Edit item

    :param item_id:
    :return mix:
    """

    # get user
    user = get_user_by_id(session['uid'])

    # Get car
    car = get_item_by_id(item_id)

    # Check the user is the owner
    if int(session['uid']) != int(car.author):
        flash('You don\'t have permission to edit it.', 'error')
        return redirect('/profile', 302)

    # Get token
    token = user.generate_auth_token(3600)

    if request.method == 'POST' and request.form['csrf_token'] == csrf_token:
        _car = dict()

        # cleaning data
        try:
            _car['description'] = clean(request.form['description'])
            _car['title'] = clean(request.form['title'])
            _car['model'] = clean(request.form['model'])
            _car['price'] = clean(request.form['price'])
            _car['brand'] = clean(request.form['brand'])
            _car['author'] = session['uid']
        except TypeError:
            flash('fields can\'t be empty', 'error')
            return render('catalog/new_car.html',
                          brands=brands,
                          csrf=csrf_token)

        # update car, create success message and redirect user
        item = update_item(_car, item_id)
        flash('Record "%s" was successfully updated' % item.title, 'success')
        return redirect('/profile', 302)

    return render('catalog/edit_car.html',
                  brands=brands,
                  car=car.serialize,
                  token=token,
                  user=user.serialize,
                  csrf_token=csrf_token)
Esempio n. 16
0
def login():
    db = database()
    if request.method == 'POST':
        user_id = request.form['user_id']
        user_passwd = request.form['user_passwd']
        info = db.validate_user(user_id, user_passwd)
        if len(info) == 1:
            session['login'] = 1
            session['user_id'] = user_id
            return redirect(url_for('home'))
        else:
            return render('login.html', message = 1)
    else:
        return render('login.html')
Esempio n. 17
0
def index(**kwargs):
    if request.args.get('submit') is not None:
        return redirect(url_for('.index', **get_params(['title', 'oldid'])),
                        code=c.REQUEST)

    normalize(['title'], kwargs)
    form = dykchecker.form.getForm()(request.form, **kwargs)
    data = dykchecker.model.Model(form=form)
    if form.validate(data):
        data.render()
        return render('page.html', tool=__name__, form=form, data=data)

    else:
        return render('index.html', tool=__name__, form=form)
Esempio n. 18
0
def reset_password(database):
    db = models.get_database(database) or abort(404)
    form = forms.ResetPasswordForm()

    if form.validate_on_submit():
        # find user by lower case email address
        user = db.session.query(
            db.User).filter_by(email=form.email.data.lower()).first()
        if not user or not user.verified:
            if not user: flash('No account with this e-mail address exists.')
            if user and not user.verified:
                flash('Account was not verified yet.')
            return render('/accounts/reset_password.html',
                          db=db,
                          database=database,
                          form=form)

        hash = hashlib.sha256()
        hash.update(config.SECRET_KEY)
        hash.update(user.email)
        hash.update(str(datetime.datetime.now()))
        hash.update(user.password)
        # reuse the activation hash (user should be activated at this point already)
        user.activation_hash = 'pw_reset_' + hash.hexdigest()

        try:
            db.session.commit()

            msg = Message("[" + db.label + "] Password reset instructions",
                          recipients=[user.email])
            msg.body = "Dear " + user.firstname + " " + user.lastname + ",\n\n" + \
                       "If you did not use the password reset link on the website ignore this mail.\n\n" + \
                       "To reset your password please use the following link:\n" + \
                       request.url_root[:-1] + url_for('accounts.change_password', database=database,
                                                       reset_hash=hash.hexdigest())
            mail.send(msg)

            flash(
                'E-mail was sent. Please refer to the mail for further instructions.'
            )
        except Exception as e:
            print e
            flash(
                'Could not send reset mail. Please contact an administrator.')

    return render('/accounts/reset_password.html',
                  db=db,
                  database=database,
                  form=form)
Esempio n. 19
0
def history():
    try:
        if session['email']:

            # ดึงข้อมูลช่วง วัน เวลา และ ชื่อ ของการแจ้งเตือน
            cur = conn.cursor()
            sql = 'SELECT alert_name,alert_date,alert_time FROM alerts_member WHERE member_email = %s'
            cur.execute(sql, (session['email']))
            datetimes = cur.fetchall()

            date_list = []  # สร้าง list เก็บข้อมูล วัน ที่ SELECT ออกมา
            time_list = []  # สร้าง list เก็บข้อมูล เวลา ที่ SELECT ออกมา

            for datetime in datetimes:
                date_list.append(datetime[1])  # datetime[1] = ข้อมูล วัน
                time_list.append(datetime[2])  # datetime[2] = ข้อมูล เวลา

            date_list = list(
                dict.fromkeys(date_list))  # ลบ ข้อมูลที่ซ้ำกันใน List

            # ดึงข้อมูล line token
            cur = conn.cursor()
            sql = 'SELECT token_id,token_name FROM linetoken_member WHERE member_email = %s'
            cur.execute(sql, (session['email']))
            data_token = cur.fetchall()
            cur.close()

            if get_linetoken(session['email']):
                user_token = get_linetoken(session['email'])[0]
            else:
                user_token = get_linetoken(session['email'])

            if len(data_token) == 0:
                alert = 'กรุณาเพิ่มช่องทางสำหรับการแจ้งเตือน'
                return render('notification_history.html',
                              images=datetimes,
                              dates=date_list,
                              data_token=data_token,
                              user_token=user_token,
                              alert=alert)

            return render('notification_history.html',
                          images=datetimes,
                          dates=date_list,
                          data_token=data_token,
                          user_token=user_token)
    except:
        return render('login.html')
Esempio n. 20
0
def edit():
    '''
        Edit or modify product details
    '''
    db = sqlite3.connect(DATABASE_NAME)
    cursor = db.cursor()

    prod_id = request.form['prod_id']
    prod_name = request.form['prod_name']
    prod_quantity = request.form['prod_quantity']
    prod_price = request.form['prod_price']

    if prod_name:
        cursor.execute("UPDATE products SET prod_name = ? WHERE prod_id == ?",
                       (prod_name, str(prod_id)))
    if prod_quantity:
        cursor.execute(
            "Update products SET prod_quantity = ? WHERE prod_id == ?",
            (prod_quantity, str(prod_id)))
    if prod_price:
        cursor.execute(
            "Update products SET prod_price = ? WHERE prod_id == ? ",
            (prod_price, str(prod_id)))
    db.commit()

    return redirect(url_for('product'))

    return render(url_for(type_))
Esempio n. 21
0
def make_and_render_response(data):
    data = (json.loads(decompress(decode(str(data)))))
    headers = dict(map(lambda x: map(str.strip, str(x).split(':')), filter(None, data['headers'].split('\n'))))

    method = data['method'].lower()
    body = data['body']
    url = data['url']
    if not url.startswith('http'):
        url = 'http://' + url

    resp = methods={
        'get':requests.get,
        'post':requests.post,
        'put':requests.put,
        'delete':requests.delete,
        'head':requests.head,
        'patch':requests.patch
    }[method](url, headers=headers, data=str(body))

    content = resp.text
    if 'json' in resp.headers['content-type']:
        content = json.dumps(json.loads(resp.text),indent=4, separators=(',', ': '))
    headers = json.dumps(json.loads(json.dumps(dict(resp.headers))),indent=4, separators=(',', ': '))

    return render("response.html", resp=resp, headers=headers, content=content, data=data)
Esempio n. 22
0
def summary():

    msg = None
    q_data, warehouse, products = None, None, None

    try:
        # cursor.execute("SELECT * FROM location")
        cursor.execute("CALL getlocation()")
        warehouse = cursor.fetchall()
        #cursor.execute("SELECT * FROM product")
        cursor.execute("CALL getproduct()")
        products = cursor.fetchall()
        cursor.execute("""
        SELECT prod_name, unallocated_quality, prod_quality FROM product
        """)
        q_data = cursor.fetchall()
    except mysql.Error as e:
        msg = f"An error occurred: {e.args[0]}"
    if msg:
        print(msg)

    return render('index.html',
                  link=link,
                  title="Summary",
                  warehouses=warehouse,
                  products=products,
                  database=q_data)
Esempio n. 23
0
def ts():
	api = r.get('https://feeds.divvybikes.com/stations/stations.json')
	data = api.json()
	station = data['stationBeanList'][45]['stationName']
	docks = data['stationBeanList'][45]['availableDocks']
	bikes = data['stationBeanList'][45]['availableBikes']
	return render("index.html",docks=docks,station=station,bikes=bikes)
Esempio n. 24
0
def transactions(account):
    source = Account.get(account)

    form = TransactionForm(request.form)
    if form.validate():
        target = Account.get(form.b.data)
        # TODO: store dates in UTC
        date = datetime.strptime(form.date.data, '%Y-%m-%d')
        increase = float(form.increase.data)
        decrease = float(form.decrease.data)
        description = form.description.data

        amount = increase - decrease

        transaction = api.transactions.create(source, target, date, amount, description)

        app.logger.debug(transaction)

        # TODO: return a JSON representation of the transaction?

    for e in form.errors:
        app.logger.debug('%s: %s' % (e, form.errors[e]))

    # TODO: return an error
    return render('accounts/view.html', account=source)
Esempio n. 25
0
def index(**kwargs):
    if request.args.get('submit') is not None:
        active = request.form.get('tabStatus')
        params = ['siteDest', 'siteSource']
        if active == 'page':
            params.append('title')
        return redirect(url_for('.index', **get_params(params)), code=c.REQUEST)

    normalize(['title'], kwargs)
    if not request.form.get('tabStatus', False):
        if kwargs.get('siteDest', False) and not kwargs.get('title', False):
            kwargs['tabStatus'] = 'content'
        else:
            kwargs['tabStatus'] = 'page'

    if not request.form.get('siteDest', False) and not request.form.get('siteSource', False):
        kwargs['siteDest'] = 'th'
        kwargs['siteSource'] = 'en'

    form = wikitranslator.form.getForm()(request.form, **kwargs)
    data = wikitranslator.model.Model(form=form)
    if form.validate(data):
        data.render()
    return render('index.html',
                  tool=__name__,
                  form=form,
                  data=data)
Esempio n. 26
0
def render_template(name, **attrs):
    """Alias used to update the dict with attrs passed to the _real_
    template renderer function. Currently, we're only passing the
    resource registry to all templates.
    """
    attrs.update({ 'registry': registry })
    return render(name, **attrs)
Esempio n. 27
0
def location():

    msg = None

    cursor.execute("SELECT * FROM location")
    warehouse_data = cursor.fetchall()

    if request.method == 'POST':
        warehouse_name = request.form['warehouse_name']

        transaction_allowed = False
        if warehouse_name not in ['', ' ', None]:
            transaction_allowed = True

        if transaction_allowed:
            try:
                cursor.execute("INSERT INTO location (loc_name) VALUES (%s)",
                               (warehouse_name))
                cnx.commit()
            except mysql.Error as e:
                msg = f"An error occurred: {e.args[0]}"
            else:
                msg = f"{warehouse_name} added successfully"

            if msg:
                print(msg)

            return redirect(url_for('location'))

    return render('location.html',
                  link=link,
                  warehouses=warehouse_data,
                  transaction_message=msg,
                  title="Warehouse Locations")
Esempio n. 28
0
def summary():
    '''
    Get all products detail
    '''
    init_database()
    msg = None
    q_data, products = None, None
    db = sqlite3.connect(DATABASE_NAME)
    cursor = db.cursor()
    try:
        cursor.execute("SELECT * FROM products")
        products = cursor.fetchall()
        cursor.execute("""
        SELECT prod_name, prod_quantity, prod_price FROM products
        """)
        q_data = cursor.fetchall()
    except sqlite3.Error as e:
        msg = f"An error occurred: {e.args[0]}"
    if msg:
        print(msg)

    return render('index.html',
                  link=link,
                  title="Summary",
                  products=products,
                  database=q_data)
Esempio n. 29
0
def databases():
    """ Show a list of databases this web frontend is serving """
    databases = list(models.get_databases().itervalues())
    databases.sort(key=lambda db: db.database.lower())

    return render('/admin/databases.html', databases=databases,
                  host=config.DATABASE_HOST, port=config.DATABASE_PORT)
Esempio n. 30
0
def upload_segments(slug):
    """
    Upload segments to the given project. Segments are bundled in a
    single zip file.

    :param slug: the project slug
    """
    _project = get_project(slug)
    if _project is None:
        return missing_project(slug)

    form = ImagesForm()
    if form.validate_on_submit():
        z = ZipFile(form.path.data)

        # Extract all images to <images>/<slug>
        dir_path = images.path(slug)
        z.extractall(dir_path)

        # Create `Segment` objects for each image.
        filenames = [os.path.join(slug, f) for f in z.namelist()]
        for name in filenames:
            db.session.add(Segment(
                image_path=name,
                project_id=_project.id,
                status=Status.proofreading_1
            ))
            db.session.commit()

        flash('Uploaded %s images.' % len(filenames))

    return render('upload-segments.html', form=form)
Esempio n. 31
0
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        flash(f'Account created for {form.username.data}!', 'success')
        return redirect(url_for('home'))

    return render('register.html', title='Register', form=form)
Esempio n. 32
0
def summary():
    init_database()
    DATABASE_NAME = 'inventory.sqlite'
    db = sqlite3.connect(DATABASE_NAME)
    cursor = db.cursor()
    msg = None
    q_data, warehouse, products = None, None, None
    db = sqlite3.connect(DATABASE_NAME)
    cursor = db.cursor()
    try:
        cursor.execute("SELECT * FROM location")
        warehouse = cursor.fetchall()
        cursor.execute("SELECT * FROM products")
        products = cursor.fetchall()
        cursor.execute("""
        SELECT prod_name, unallocated_quantity, prod_quantity FROM products
        """)
        q_data = cursor.fetchall()
    except sqlite3.Error as e:
        msg = f"An error occurred: {e.args[0]}"
    if msg:
        print(msg)

    return render('index.html',
                  link=link,
                  title="Summary",
                  warehouses=warehouse,
                  products=products,
                  database=q_data)
Esempio n. 33
0
def products():
    context = {
        'products': [{
            "code": 1
        }, {
            "code": 2
        }, {
            "code": 3
        }, {
            "code": 4
        }, {
            "code": 5
        }, {
            "code": 6
        }, {
            "code": 7
        }, {
            "code": 8
        }, {
            "code": 9
        }, {
            "code": 10
        }]
    }

    return render('index.html', **context)
Esempio n. 34
0
def index():
    """
    登录主页
    :return:
    """
    form = LoginForm()
    if form.validate_on_submit():
        ...
        user_name = request.form.get('name', None)
        password = request.form.get('pwd', None)
        user = U.query.filter_by(name=user_name).first()
        if user is not None:

            # print("user pwd",user.pwd)
            # user = U(user_name)
            from utils import enc_pwd
            if enc_pwd(password) == user.pwd:
                ...
                # print("is_loging")
                login_user(user)
                return redirect(url_for(".details"))
            else:
                flash('密码错误.')
        flash('账号错误.')
    return render('index/index.html', form=form)
Esempio n. 35
0
def details():
    if request.method == 'GET':
        # print("log for current_user", current_user.__dict__, type(current_user.__dict__))
        return render("index/details.html")
    elif request.method == "POST":
        del current_user.__dict__['_sa_instance_state']
        return jsonify(current_user.__dict__)
Esempio n. 36
0
def invite(id):
    circle = required(db.session.query(Circle).filter_by(id=id).first())
    member = check_access(circle, member_required=True)
    make_invitations(circle, member)
    db.session.commit()
    invitations = invitations_for_circle(circle, member)
    return render('invite.html', circle=circle, invitations=invitations)
Esempio n. 37
0
def index():    
    msg = ""
    init_database()
    db = sqlite3.connect(DATABASE_NAME)
    cursor = db.cursor()

    if request.method == 'POST':
        #session.pop('username', None)
        username = str(request.form["user"])
        password = str(request.form["password"])
        print(username, password)
        
        cursor.execute("SELECT * from user where nombreUsuario = ? and contraseña = ?", (username, password))
        data = cursor.fetchall()
        if len(data) == 1:
            session['logged_in'] = True
            session['user'] = username
            session['pass'] = password
        else:        
            msg = "Wrong Credentials"

    if not session.get('logged_in'):
        return render("index.html", title="Login", msg=msg)
    else:
        return redirect(url_for("home"))
Esempio n. 38
0
def join_circle(id):
    circle = get_required(Circle, id)
    required(str(circle.id) in g.invitations)

    if not g.user:
        flash("Before you can join a circle, you must be logged in.")
        return redirect(url_for('login'))

    invitations = get_active_invitations_for_circle(circle.id)
    form = JoinCircleForm(request.form)

    if request.method == 'POST' and form.validate():
        nickname = form.nickname.data
	member = Member(circle=circle, user=g.user)
        form.populate_obj(member)
        db.session.add(member)

        for invitation in invitations:
            invitation.acceptor = member

        db.session.commit()

        # delete the temporary invitation
        del g.invitations[str(circle.id)]
        save_active_invitations()

        flash("You're a member now!  Your nickname here is %s." % nickname)
        return redirect(circle.url)

    return render('join_circle.html', circle=circle, form=form, invitations=invitations)
Esempio n. 39
0
def index():
    print('hello')
    hint = "请选择一到两个职位查看可视化的数据"
    job_items = ['区块链', '大数据', '人工智能', '物联网', '云计算']
    chartCode = []
    chartCode1 = []
    name_list = []
    for j in job_items:
        data = vd.splitProvince(j)
        m1 = Markup(
            vd.map_chart(data['number'].items(), '职位数量统计',
                         '各省' + j + '职位数量统计').render_embed())

        # name_list.append(j+'-岗位数')
        salary = data['salary'].items()
        m2 = Markup(
            vd.map_chart(salary, '最低薪资平均水平统计',
                         '各省' + j + '最低薪资平均水平统计').render_embed())
        chartCode.append([m1, m2])
    # name_list.append(j+'-薪资水平')

    return render(
        'index.html',
        #number_tab=Markup(vd.tab_charts(chartCode,job_items).render_embed())
        name_list=job_items,
        chart=chartCode)
Esempio n. 40
0
def archive(page=None):
    data = categorymover.model.Model()
    data.getArchive()
    return render('list.html',
                  tool=__name__,
                  data=data,
                  mode='archive')
Esempio n. 41
0
def location():
    init_database()
    msg = None
    db = sqlite3.connect(DATABASE_NAME)
    cursor = db.cursor()

    cursor.execute("SELECT * FROM location")
    warehouse_data = cursor.fetchall()    

    if request.method == 'POST':
        warehouse_name = request.form['warehouse_name']

        transaction_allowed = False
        if warehouse_name not in ['', ' ', None]:
            transaction_allowed = True

        if transaction_allowed:
            try:
                cursor.execute("INSERT INTO location (loc_name) VALUES (?)", (warehouse_name,))
                db.commit()
            except sqlite3.Error as e:
                msg = f"An error occurred: {e.args[0]}"
            else:
                msg = f"{warehouse_name} added successfully"

            if msg:
                print(msg)

            return redirect(url_for('location'))

    return render('location.html', link=link, warehouses=warehouse_data, transaction_message=msg, title="Sucursales")
Esempio n. 42
0
def queue():
    data = categorymover.model.Model()
    data.getQueue()
    return render('list.html',
                  tool=__name__,
                  data=data,
                  mode='queue')
Esempio n. 43
0
def _reset_password(code):
    from worker import passwd
    from rankey import rankey
    from sender import sendre
    from signer import loads
    try:
        username, expired = loads(code)
        if not expired:
            password = rankey(9)
            passwd(username, password)
            sendre(password, username)
            reset_session()
            return render('reset_password.html', title='重设密码成功')
        return render('reset_password.html', title='重设密码过期')
    except:
        return render('reset_password.html', title='重设密码失败')
Esempio n. 44
0
def text(**kwargs):
    if request.args.get('submit') is not None:
        active = request.form.get('tabStatus')
        params = []
        if active == 'page':
            mode = 'page'
            params.append('title')
        else:
            mode = 'content'
        return redirect(url_for('.text', mode=mode, **get_params(params)), code=c.REQUEST)

    if not request.form.get('tabStatus', False):
        if kwargs.get('mode', None) == 'page':
            kwargs['tabStatus'] = 'page'
        else:
            kwargs['tabStatus'] = 'content'

    form = contribtracker.form.getForm()(request.form, **kwargs)
    data = contribtracker.model.Model(form=form)

    if form.validate(data):
        data.render()
    return render('index.html',
                  tool=__name__,
                  form=form,
                  data=data)
Esempio n. 45
0
def show_circle(id):
    circle = required(db.session.query(Circle).filter_by(id=id).first())
    you = check_access(circle)
    discussion_form = CommentForm(request.form)
    postings = db.session.query(Posting).filter_by(circle_id=circle.id).order_by(Posting.last_bumped.desc())
    
    return render('circle.html', circle=circle, discussion_form=discussion_form, postings=postings, you=you)
Esempio n. 46
0
def show_picture(circle_id, posting_id):
    posting = get_required(Posting, posting_id)
    if circle_id != posting.circle_id:
        raise Http404
    circle = posting.circle
    you = check_access(circle)
    discussion_form = CommentForm(request.form)
    return render('photo.html', circle=circle, posting=posting, you=you, discussion_form=discussion_form)
Esempio n. 47
0
def index():
    user = api.users.get_current_user()
    accounts = []

    for company in user.companies:
        accounts.extend([a for a in company.accounts])

    return render('accounts/index.html', user=user, accounts=accounts)
def show_tags(namespace=None, repository=None):
    if repository is not None: _query = namespace + '/' + repository
    uri = '/v1/repositories/' + _query + '/tags'
    if request.method == 'POST': uri = '/v1/repositories/' + str(request.values['name']) + '/tags'
    msg = registry.act(server, uri=uri, verbose=True)
    msg['tableheader'] = ['Tag', 'ID']
    _tree_json = '/json/' + _query
    return render('tags.html', pagetitle='images', tree_json=_tree_json, msg=msg)
Esempio n. 49
0
def home():
    db = database()
    if session.get('login', 0) == 0:
        return redirect(url_for('login'))
    else:
        user = db.get_user(session['user_id'])
        courses = db.get_courses(session['user_id'])
        return render('home.html' , user = user, courses = courses)
def main_page():
    _registryhost = configuration.server
    _status = ping_server()
    _t = registry.get('/v1/search?q=')
    _imagenumber = ''
    if isinstance(_t, dict): _imagenumber = _t['num_results']

    return render('index.html', pagetitle='index', imagenumber=_imagenumber, hosts=_registryhost, status=_status)
def show_tags(namespace=None, repository=None):
    if repository is not None: _query = namespace + '/' + repository
    if request.method == 'POST': _query = str(request.values['name'])
    uri = '/v1/repositories/' + _query + '/tags'
    msg = registry.act(uri=uri, verbose=True)
    _tableheader = ['Name', 'ID', 'Actions']
    _tree_json = '/json/' + _query
    return render('tags.html', pagetitle='tags', tree_json=_tree_json, msg=msg, tableheader=_tableheader, reponame=_query)
def find_image(text=None):
    if request.method == 'POST':
        uri = '/v1/search?q=' + request.values['name']
    if text:
        uri = '/v1/search?q=' + str(text)
    msg = registry.get(uri=uri, verbose=True)
    _tableheader = ['Name', 'Description', 'Actions']
    return render('images.html', pagetitle='images', msg=msg, tableheader=_tableheader)
Esempio n. 53
0
def course(course_id):
    db = database()
    if session.get('login', 0) == 0:
        return redirect(url_for('login'))
    else:
        course = db.get_course_from_id(session['user_id'], course_id)
        homework = db.get_homework(session['user_id'], course_id)
        return render('course.html', course = course, homework = homework)
Esempio n. 54
0
File: views.py Progetto: kopf/ahye
def crossload(url):
    if not url.startswith('http:/') and not url.startswith('https:/'):
        abort(404)

    # reconstruct url (query string has been stripped from url by flask)
    if request.query_string:
        url = '%s?%s' % (url, request.query_string)

    # rewrite url as apache's mod_rewrite converts // to /
    if url.startswith('http:/') and not url.startswith('http://'):
        url = url.replace('http:/', 'http://')
    elif url.startswith('https:/') and not url.startswith('https://'):
        url = url.replace('https:/', 'https://')

    filename = '%s%s' % (hashlib.md5(url.encode('utf-8')).hexdigest(),
                         guess_file_extension(url))

    parsed_url = urlparse.urlparse(url)
    auth = (parsed_url.username, parsed_url.password)

    if not os.path.exists(os.path.join(LOCAL_UPLOADS_DIR, filename)):
        try:
            conn = requests.get(url, auth=auth, verify=False)
        except requests.exceptions.ConnectionError:
            return render('/error.html',
                          error={'msgs': ['Connection to server failed.',
                                          'Is it a valid domain?']})
        except (requests.exceptions.InvalidSchema,
                requests.exceptions.MissingSchema,
                requests.exceptions.InvalidURL):
            return render('/error.html',
                          error={'msgs': ['Invalid URL.',
                                          'Please check and try again.']})
        except requests.exceptions.Timeout:
            return render('/error.html',
                          error={'msgs': ['Connection to server timed out.']})
        except Exception:
            return render('/error.html')

        if 200 <= conn.status_code <= 300:
            with open(os.path.join(LOCAL_UPLOADS_DIR, filename), 'w') as f:
                f.write(conn.content)
        else:
            return render('/error.html', error={'code': conn.status_code})
    return redirect(url_for('serve_upload', filename=filename, _external=True))
def show_info(id=None):
    _uri = '/v1/images/' + id + '/json'
    _msg = registry.act(uri=_uri, verbose=True)
    _msg['tableheader'] = ['Tag', 'ID']
    _uri = '/v1/images/' + id + '/ancestry'
    _ancestry = {}
    _ancestry['tableheader'] = 'Ancestry'
    _ancestry['data'] = registry.act(uri=_uri)
    return render('info.html', pagetitle='images', msg=_msg, ancestry=_ancestry)
Esempio n. 56
0
def pdu_graph(pdu_id):
	import traceback
	try:
		#username = request.cookies.get('username')
		username = "******"
		return render("graph.jade",title="PDU Graph",user=username,pdu_id=pdu_id,isOnline=isPDUOnline(pdu_id))
	except Exception, e:
		print e
		traceback.print_exc()
Esempio n. 57
0
def create():
    form = CreateCompanyForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User(document=form.document.data, name=form.username.data, email=form.email.data, password=form.password.data)
        company = Company.create(nit=form.nit.data, name=form.name.data, user=user)
        user.put()
        company.put()
        app.logger.debug(company)
        app.logger.debug(user)
    return render('companies/create.html', form=form)
Esempio n. 58
0
def nodes():    
    try:
        instanceList = aws.getAllNodes("t2.micro","running")
        #print instanceList
        ilist = instanceList['Reservations']
        print ilist
        
        return render("nodes.html", instances=ilist)
    except:
        traceback.print_exc()
        return Response('{ "message":"Unable to get Node List" }', 400, mimetype='application/json')
Esempio n. 59
0
def _add():
    form = {}
    if request.method == 'POST':
        if request.form['title']:
            c = Element(title=request.form['title'])
            db.session.add(c)
            db.session.commit()
            return redirect(url_for('admin._all'))
        else:
            form['title_error'] = u'This field is required'
    return render('form.html', form=form)
Esempio n. 60
0
def showCFVariables():
    cf_var_dict = {}

    # Get all environment variables from the CF application container
    for k in os.environ:
        cf_var_dict[k] = os.getenv(k)

    # Get the HTTP request header
    headers = request.headers

    return render('index.html', cf_variables=cf_var_dict, http_headers=headers)