예제 #1
0
	def select_user(self, user_to_move='', dest_server='', ignore_users=[]):
		"""Return a candidate for migration"""
		self.user_to_move = user_to_move
		self.dest_server = dest_server
		if len(ignore_users) > 0:
			self.ignore_users.extend(ignore_users)
		self.template = Templates(self.log, self.user_to_move, self.dest_server, self.homes)
		if self.user_to_move == '':
			self.source_home = self.template.prompt_home_selection()[1]
			self.log.debug("User selected: " + self.source_home)
			self.quotas = self.fs_utils.get_quota(self.source_home) # OrderedDict({username:quota})
			self.log.debug("Quota results:\n" + '\n'.join([str(user) + " : " + str(quota) for user, quota in self.quotas.items()]))

			for u in self.ignore_users:
				self.quotas.pop(u, None)

			# For now, we only consider the top 10
			if len(self.quotas) > 10:
				self.quotas = OrderedDict(self.quotas.items()[0:10])

			# create a list of User objects
			for u in self.quotas.items():
				self.users.append(User(u[0], u[1], self.check_dns(self.get_list_of_domains(u[0])), self.is_resold(u[0])))
			print ""
			self.migrate_user = self.template.prompt_user_selection(self.users, self.reseller_list) # User object is returned.
			#Get users homedir
			self.migrate_user.home_dir = os.path.expanduser('~' + self.migrate_user.user_name)
			while not (os.path.isdir(self.migrate_user.home_dir) and self.migrate_user.home_dir.startswith('/home')):
				print(bgcolors.RED + "Couldn't determine " + self.migrate_user.user_name + "'s home directory." + bgcolors.END)
				self.log.debug("Couldn't determine " + self.migrate_user.user_name + "'s home directory.")
				self.migrate_user.home_dir = raw_input("Enter home directory of " + self.migrate_user.user_name + " >> ")
			return self.migrate_user
예제 #2
0
 def render(self):
     card_select_template = Templates.get('payment_card_select.html')
     if self.variant == 'success':
         self.data_context['form_message'] = 'Default payment method is successfully set'
         self.content = card_select_template.render(self.data_context)
     elif self.variant == 'paybot':
         cards_list_template = Templates.get('payment_cards_list.html')
         self.content = cards_list_template.render(self.data_context)
     else:
         self.content = card_select_template.render(self.data_context)
     return super().render()
예제 #3
0
    def expandTemplates(self, genDir, template, outFileMask, filenameProp, objects, objectName, baseVars=None  ):
        for item in objects.values():
            print( "Expanding template '%s' for: %s" % (template, item[filenameProp]))

            vars = baseVars.copy() if baseVars else {}
            vars['GEN_DIR'] = genDir
            
            for k in item:
                vars[objectName+"_"+k] = item[k]

            Templates.mergeToFile(self.templatesDir + template, outFileMask.format(item[filenameProp]), vars )
예제 #4
0
    def createTemplates(self, useLabels=True):
        """ create mention and number templates for entity in each sentence in the list of abstracts
            if useLabels is True, then detected mentions and numbers are used for templates
            otherwise use annotated information.

            this also creates annotated templates regardless. """
        for abstract in self.__list:
            for sentence in abstract.sentences:
                sentence.templates = Templates(sentence, useLabels=useLabels)
                sentence.annotatedTemplates = Templates(sentence,
                                                        useLabels=False)
예제 #5
0
 def generateConfigForTFTP(self, genDir):
     self.expandTemplates(genDir, 'tftp/pxelinux_cfg_default_for_image.txt',
                          genDir + "/default_for_{}", 'name', self.images,
                          'image', self.baseVars)
     self.expandTemplates(genDir, 'tftp/boot_msg_for_image.txt',
                          genDir + "/boot_msg_for_{}", 'name', self.images,
                          'image', self.baseVars)
     self.expandTemplates(genDir, 'tftp/setup_tftp_for_image.sh',
                          genDir + "/setup_tftp_for_{}.sh", 'name',
                          self.images, 'image', self.baseVars)
     Templates.mergeToFile(self.templatesDir + 'tftp/mount_image.sh',
                           genDir + '/mount_image.sh', {})
예제 #6
0
def handle_message(event):
    try:
        rich_menu_id = line_bot_api.get_rich_menu_id_of_user(
            event.source.user_id)
    except:
        rich_menu_id = config.BORROW_RICH_MENU
    if rich_menu_id == config.BORROW_RICH_MENU:
        action = "borrow"
    else:
        action = "return"
    if isinstance(event.message, LocationMessage):
        now = datetime.now(pytz.timezone("Asia/Taipei"))
        current_time = now.strftime("%Y/%m/%d %H:%M:%S")
        latitude = float(event.message.latitude)
        longitude = float(event.message.longitude)

        youbike_1 = search(bike_type=1,
                           latitude=latitude,
                           longitude=longitude,
                           max_distance=500)
        youbike_2 = search(bike_type=2,
                           latitude=latitude,
                           longitude=longitude,
                           max_distance=200)
        if len(youbike_1) == 0 and len(youbike_2) == 0:
            message = TextSendMessage(text="很抱歉!\n您所在的位置附近並沒有YouBike站點!")
            line_bot_api.reply_message(event.reply_token, message)
        else:
            youbike1_data = Templates().bike_data(
                results=youbike_1,
                user_lat=latitude,
                user_lng=longitude,
                bike_type=1,
                action=action,
            )
            youbike2_data = Templates().bike_data(
                results=youbike_2,
                user_lat=latitude,
                user_lng=longitude,
                bike_type=2,
                action=action,
            )
            message = youbike1_data + youbike2_data
            line_bot_api.reply_message(event.reply_token, message)

        history_data = {
            "uuid": event.source.user_id,
            "time": current_time,
            "loc": [latitude, longitude],
            "action": action,
        }
        config.db["History"].insert(history_data)
예제 #7
0
 def render(self):
     template = Templates.get('layout.html')
     self.data_context['title'] = self.title
     self.data_context['greetings'] = self.greetings
     self.data_context['content'] = self.content
     page = template.render(self.data_context)
     return page
예제 #8
0
	def register_user():
		name = request.form['name']
		lastname = request.form['lastname']
		email =  request.form['email']
		password = request.form['password']
		phote = request.files['file']


		if phote and allowed_file(phote.filename):
			    # Make the filename safe, remove unsupported chars
			filename = secure_filename(phote.filename)
			    # Move the file form the temporal folder to
			    # the upload folder we setup
			if not os.path.exists(fullpath):
				#The folder to send the file if something is goes wrong
				PATH  ='C:\\Users\hacker\desktop\startup\machine\Assets\empyt_folder'
				#config path folder
				app.config['UPLOAD_FOLD'] = PATH
				#changing dir
				os.chdir('C:\\users\hacker\desktop\startup\machine\static\Assets')
				# make a new folder
				os.mkdir("empyt_folder")
				file_name =  secure_filename(phote.filename)
				phote.save(os.path.join(app.config['UPLOAD_FOLD'],file_name))
				Users.registration(reguest.form['name'], request.form['lastname'], equest.form['email'],request.form['password'],filename)
			else:
				filename =  secure_filename(phote.filename)
				phote.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
				Users.registration(request.form['name'] ,request.form['lastname'],request.form['email'],request.form['password'],filename)
			#return redirect(url_for('uploaded_file',filename=filename))
		return redirect(url_for(Templates.elslogin('login')))
예제 #9
0
 def render(self):
     template = Templates.get('layout.html')
     self.data_context['title'] = self.title
     self.data_context['greetings'] = self.greetings
     self.data_context['content'] = self.content
     page = template.render(self.data_context)
     return page
예제 #10
0
    def list_existing_machines():
        """ Lists all defined machines on the host (without considering the templates)
        :return: List of names of the machines
        """
        all_machines_list = Templates('').list_templates()
        machine_list = list(
            filter(lambda x: not x.startswith('template_'), all_machines_list))

        return machine_list
예제 #11
0
    def render(self):
        self.pages = { 'index': 'index.html' }
        if ('user_name' in self.data_context) and \
           (self.data_context['user_name'] is not None):
            self.greetings = 'Hello! You\'ve logged in as {0}'.format(self.data_context['user_name'])
        else:
            self.data_context['login_form'] = Templates.get('login_form.html').render()

        self.index(self.pages[self.variant])
        return super().render()
예제 #12
0
def handle_follow(event):
    now = datetime.now(pytz.timezone("Asia/Taipei"))
    current_time = now.strftime("%Y/%m/%d %H:%M:%S")
    user = {
        "uuid": event.source.user_id,
        "time": current_time,
        "action": "borrow",
    }
    config.db["User List"].insert(user)
    message = Templates().welcome_message()
    line_bot_api.reply_message(event.reply_token, message)
예제 #13
0
    def render(self):
        self.pages = {'index': 'index.html'}
        if ('user_name' in self.data_context) and \
           (self.data_context['user_name'] is not None):
            self.greetings = 'Hello! You\'ve logged in as {0}'.format(
                self.data_context['user_name'])
        else:
            self.data_context['login_form'] = Templates.get(
                'login_form.html').render()

        self.index(self.pages[self.variant])
        return super().render()
예제 #14
0
def generate_grade_files():
    course = app.get_course()
    assignment = app.get_assignment()

    header = [['Assignment Name:', assignment.name], ['Due Date:', assignment.due_at],
              ['Points Possible:', assignment.points_possible], ['Extra Points:', '0'], ['Score Type:', 'POINTS'],
              ['Student Num', 'Student Name', 'Score']]

    entries = {}
    for column in course.get_custom_columns():
        if column.title == 'Notes':
            entries = {entry.user_id: entry.content for entry in column.get_entries(course)}

    if not entries:
        logging.warning("No scholar ids found in "+course.name)
        return

    grades = {}
    ids = []
    for submission in assignment.get_submissions():
        grade = submission.attributes['grade']
        grades[entries[submission.user_id]] = {'Name:': course.get_user(submission.user_id).name, 'Grade:': grade}
        ids.append(entries[submission.user_id])

    for label, template in Templates().templates.iteritems():
        if [value for value in Templates().get_ids(template) if value in ids]:
            filename = template['Class:'] + '_'  +label
            with open(filename+'.csv', 'w') as pstfile:
                writer = csv.writer(pstfile, quoting=csv.QUOTE_MINIMAL)

                writer.writerow(['Teacher Name:', template['Teacher Name:']])
                writer.writerow(['Class:', template['Class:']])

                for row in header:
                    writer.writerow(row)
                for row in template['Scholars']:
                    if row[0] in grades.keys():
                        writer.writerow([row[0], row[1], grades[row[0]]['Grade:']])
                    else:
                        writer.writerow([row[0], row[1], None])
예제 #15
0
    def __init__(self, DBCONN, args, staticDir):
        self.DBCONN = DBCONN
        self.args = args
        self.staticDir = staticDir

        viewDir = os.path.join(os.path.dirname(__file__), "../../views")
        self.templates = Templates(viewDir)

        self.host = "http://zlab-annotations.umassmed.edu/"
        if self.args.local:
            fnp = os.path.expanduser("~/.ws_host.txt")
            if os.path.exists(fnp):
                self.host = open(fnp).read().strip()
예제 #16
0
    def __init__(self):
        self.templates = Templates()
        self.matcher = Matcher(nlp.vocab)
        self.tokenizer = Tokenizer()
        self.current_method_parts = None
        self.current_code = '\n'
        var_equals_number = [{
            'ORTH': '@throws'
        }, {
            'POS': 'PROPN'
        }, {
            'ORTH': 'if'
        }, {
            'TEXT': {
                'REGEX': '\w*'
            }
        }, {
            'TEXT': {
                'REGEX': '\s*'
            }
        }, {
            'ORTH': '{'
        }, {
            'ORTH': '@code'
        }, {
            'POS': 'PROPN'
        }, {
            'ORTH': '}'
        }, {
            'TEXT': {
                'REGEX': '\w*'
            }
        }, {
            'Pos': 'NUM'
        }]

        self.matcher.add("var_equals_number", self.on_match_var_equals_number,
                         var_equals_number)
예제 #17
0
    def __init__(self, args):
        self.args = args

        viewDir = os.path.join(os.path.dirname(__file__), "views")
        self.templates = Templates(viewDir)

        self.staticDir = os.path.realpath(
            os.path.join(os.path.dirname(__file__), "views/static"))
        self.config = {
            '/static': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': self.staticDir
            }
        }
예제 #18
0
def main():
    parser = argparse.ArgumentParser(description='Maven based download index generator')
    parser.add_argument('--webout', dest='output_web', default='/out', help='Base directory to output generated index pages. Will generate in sub-directories based on the maven path', type=parse_path)
    parser.add_argument('--metaout', dest='output_meta', default='/out', help='Base directory to output generated metadata. Will generate in sub-directories based on the maven path', type=parse_path)
    parser.add_argument('--downloadroot', dest='dlroot', default='https://maven.minecraftforge.net/', help='Root URL for downloading artifacts')
    parser.add_argument('--webroot', dest='webroot', default='https://files.minecraftforge.net', help='Root URL for artifact pages')
    parser.add_argument('--static', dest='static', default='https://files.minecraftforge.net/static/', help='Root URL for static assets used by the templates')

    parser.add_argument('--folder', dest='folder', default='/in/repositories/releases/', help='Root directory for the maven structure to read metadata from files', type=parse_path)
    parser.add_argument('--config', dest='config', default='/in/global_overrides.json', help="Location of global_overrides.json file", type=parse_path)
    parser.add_argument('--templates', dest='templates', default='templates', type=parse_path, help="Path to templates")

    commands = parser.add_subparsers(help='Command to perform', dest='command', required=True)

    gen_command = commands.add_parser('gen', help='Indexes generator subcommand')
    gen_command.add_argument('artifact', help='Maven Artifact - net.minecraftforge:forge')

    promote_command = commands.add_parser('promote', help='Promote subcommand')
    promote_command.add_argument('artifact',  help='Maven Artifact - net.minecraftforge:forge')
    promote_command.add_argument('version', help='Maven Version')
    promote_command.add_argument('type', choices=['latest', 'recommended'], help='Type of promotion')
    args = parser.parse_args()

    print('Page Generator:')
    print(f'PyVer:    {sys.version}')
    print(f'Folder:   {args.folder}')
    print(f'Config:   {args.config}')
    print(f'Web Out:  {args.output_web}')
    print(f'Meta Out: {args.output_meta}')
    print(f'WebRoot:  {args.webroot}')
    print(f'DLRoot:   {args.dlroot}')
    print(f'Static:   {args.static}')
    print(f'Templates:{args.templates}')
    print(f'Command:  {args.command}')
    print(f'Artifact: {args.artifact if "artifact" in args else None}')
    print(f'Version:  {args.version if "version" in args else None}')
    print(f'Type:     {args.type if "type" in args else None}')

    metadata = Metadata(args.folder, args.output_meta, args.output_web, args.webroot, args.dlroot, args.static, args.config)
    artifact = Artifact.load_maven_xml(metadata, args.artifact)
    templates = Templates(args.templates, args.static, args.webroot, args.dlroot)

    for gen in Generators[args.command]:
        gen.generate(metadata, artifact, templates, args)
예제 #19
0
    def __init__(self, DBCONN, args, wepigenomes):
        self.args = args

        self.db = DbTrackhub(DBCONN)
        self.db_bed_overlap = DbBedOverlap(DBCONN)
        self.sessions = Sessions(DBCONN)
        self.dbSnps = dbSnps(DBCONN)
        self.genes = LookupGenes(DBCONN)
        self.wepigenomes = wepigenomes
        self.urlStatus = UrlStatusDB(DBCONN)

        viewDir = os.path.join(os.path.dirname(__file__), "../../views")
        self.templates = Templates(viewDir)

        self.host = "http://zlab-annotations.umassmed.edu/"
        if self.args.local:
            fnp = os.path.expanduser("~/.ws_host.txt")
            if os.path.exists(fnp):
                self.host = open(fnp).read().strip()
예제 #20
0
def handle_postback(event):
    # 路線規劃
    if "route" in event.postback.data:
        user_lat, user_lng, bike_lat, bike_lng = event.postback.data.split(
            "_")[1].split(",")
        message = Templates().route(user_lat=user_lat,
                                    user_lng=user_lng,
                                    lat=bike_lat,
                                    lng=bike_lng)
        line_bot_api.reply_message(event.reply_token, message)
    # 借 / 還車
    elif "action" in event.postback.data:
        action = event.postback.data.split("_")[1]
        if action == "borrow":
            line_bot_api.link_rich_menu_to_user(event.source.user_id,
                                                config.RETURN_RICH_MENU)
            message = TextSendMessage(text="切換模式:還車")
        else:
            line_bot_api.link_rich_menu_to_user(event.source.user_id,
                                                config.BORROW_RICH_MENU)
            message = TextSendMessage(text="切換模式:借車")
        line_bot_api.reply_message(event.reply_token, message)
예제 #21
0
    def __init__(self, DBCONN, args, globalStaticDir):
        self.args = args

        self.db = DbTrackhub(DBCONN)
        self.sessions = Sessions(DBCONN)
        self.dbSnps = dbSnps(DBCONN)
        self.genes = LookupGenes(DBCONN)
        self.urlStatus = UrlStatusDB(DBCONN)
        self.wepigenomes = WebEpigenomesLoader(self.args)  # , HiCSiteInfo)
        self.defaults = Defaults()
        self.epigenome_stats = EpigenomeStats(
            self.wepigenomes)  # , HiCSiteInfo)

        viewDir = os.path.join(os.path.dirname(__file__), "../../views")
        self.templates = Templates(viewDir)

        self.host = "http://zlab-annotations.umassmed.edu/"
        if self.args.local:
            fnp = os.path.expanduser("~/.ws_host.txt")
            if os.path.exists(fnp):
                self.host = open(fnp).read().strip()
        self.host += HiCSiteInfo.site + "/"

        self.staticDir = os.path.join(globalStaticDir, "hic")
예제 #22
0
	def forget():
		return render_templates(Templates.restpass("restpass.html"))
예제 #23
0
파일: __init__.py 프로젝트: smhjn/condorpy
# Copyright (c) 2015 Scott Christensen
#
# This file is part of condorpy
#
# condorpy is free software: you can redistribute it and/or modify it under
# the terms of the BSD 2-Clause License. A copy of the BSD 2-Clause License
# should have be distributed with this file.

from job import Job
from dag import DAG, Node
from templates import Templates
Templates = Templates()
Templates.load()
예제 #24
0
 def index(self, template_file):
     template = Templates.get(template_file)
     self.content = template.render(self.data_context)
예제 #25
0
 def __init__(self):
     viewDir = os.path.join(os.path.dirname(__file__), "../views")
     self.templates = Templates(viewDir)
예제 #26
0
    '''
    new_forms = Forms(line.split(" ")[1].split("(")[0])
    line = f.readline()
    while line and not line.startswith("class"):
        if _tag in line:
            data = line.strip().split("=", 1)
            field = Field(data[0].strip())  # pega o nome do campo
            field.type = data[1].strip().split("(")[1]  # pega o tipo do campo
            for op in data[1].split(_tag)[1].strip().split(_delimiter):  # atributos do field
                attr = op.split("=", 1)
                if attr[0]:  # se tiver key. pode ter campo em branco
                    field.attrs[attr[0].strip()] = attr[1]

            new_forms.fields.append(field)
        line = f.readline()
    forms.append(new_forms)
    return line


parse_model(_file)

#for f in forms:
#    print f

widgets = ""
for form in forms:
    for field in form.fields:
        widgets = widgets + Templates.generate_widget(field) + "\n"

print widgets
예제 #27
0
    when = c.data.split('_')[3]
    keyboard = templates.HOURS_INLINE(when)
    bot.answer_callback_query(c.id)
    bot.edit_message_text("Set hour:",
                          message.chat.id,
                          message.message_id,
                          reply_markup=keyboard)


@bot.callback_query_handler(func=lambda c: c.data.startswith('min'))
def change_minute(c: telebot.types.CallbackQuery):
    if not check_admin_rights(c):
        return
    message = c.message
    when = c.data.split('_')[1]
    m = c.data.split('_')[2]
    atlas.change_minute(message.chat.id, when, m)
    time = atlas.time(message.chat.id, when)
    bot.answer_callback_query(c.id, "Time is changed to " + time)


if __name__ == '__main__':
    atlas = Atlas()
    templates = Templates(atlas)
    sender = Sender()
    sender.start()
    try:
        bot.polling(none_stop=True)
    except:
        pass
예제 #28
0
pygame.display.set_caption("Conway's Game of Life")
playing = True
started = False
cell_horizontal = 100
cell_vertical = 100


def gen_grid(width, height):
    arr = []
    for i in range(height):
        arr.append([0 for i in range(width)])
    return arr


map_array = gen_grid(cell_horizontal, cell_vertical)
templates = Templates(map_array)


def draw_grid():
    for i in range(len(map_array)):
        pygame.draw.line(window, (100, 100, 100),
                         (0, (height / len(map_array) * i)),
                         (width, (height / len(map_array) * i)))
        for j in range(len(map_array[i])):
            pygame.draw.line(window, (100, 100, 100),
                             ((width / len(map_array[i]) * j), 0),
                             ((width / len(map_array[i])) * j, height))


def draw_cells():
    for i in range(len(map_array)):
예제 #29
0
 def index(self, template_file):
     template = Templates.get(template_file)
     self.content = template.render(self.data_context)
예제 #30
0
class TestsProducer:
    def __init__(self):
        self.templates = Templates()
        self.matcher = Matcher(nlp.vocab)
        self.tokenizer = Tokenizer()
        self.current_method_parts = None
        self.current_code = '\n'
        var_equals_number = [{
            'ORTH': '@throws'
        }, {
            'POS': 'PROPN'
        }, {
            'ORTH': 'if'
        }, {
            'TEXT': {
                'REGEX': '\w*'
            }
        }, {
            'TEXT': {
                'REGEX': '\s*'
            }
        }, {
            'ORTH': '{'
        }, {
            'ORTH': '@code'
        }, {
            'POS': 'PROPN'
        }, {
            'ORTH': '}'
        }, {
            'TEXT': {
                'REGEX': '\w*'
            }
        }, {
            'Pos': 'NUM'
        }]

        self.matcher.add("var_equals_number", self.on_match_var_equals_number,
                         var_equals_number)

    def produce_test(self, method_parts):
        self.current_method_parts = method_parts
        javadoc = nlp(method_parts['javadoc'])
        self.matcher(javadoc)

    #=======================\/Callbacks\/=======================
    def on_match_var_equals_number(self, matcher, doc, id, matches):
        for m in matches:
            matched_text = doc[m[1]:m[2]]
            str_m = str(matched_text)
            var_name = self.tokenizer.get_var_name_on_single_line(str_m)
            exception = self.tokenizer.get_inlined_exception_name(str_m)
            right_side = self.tokenizer.get_inlined_right_value(str_m)
            parameters = []
            for parameter in self.current_method_parts['parameters']:
                value = '-1'
                if parameter[1] != var_name:
                    value = self.get_random_value(parameter[0])
                else:
                    value = right_side
                parameters.append(value)

            method_name = self.current_method_parts['method']
            method_call = self.templates.method_call(method_name, parameters)
            exception_marker = self.templates.exception_marker(exception)
            test_case = self.templates.test_case(
                exception_marker, method_name + 'Test' + exception,
                method_call)
            self.current_code = self.current_code + test_case
            #print(method_call)
            #print(matched_text)
            #print(exception)
            #print(var_name)
            #print(right_side)
            #print('-----')
            #print(test_case)
            #print('\n')
        test_content = self.templates.test_file('Test', self.current_code)
        print(test_content)
        print('\n')

    #=======================/\Callbacks/\=======================
    def get_random_value(self, value_type):
        if value_type == 'int':
            return random.randrange(-100, 100)
        elif value_type == 'long':
            return random.random()
예제 #31
0
class mainRouters(object):
	def __init__(self,app):
		fullpath ="c:\\Users\hacker\desktop\startup\machine\static\Assets\images"
		app.config['UPLOAD_FOLDER'] = fullpath
		app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

	#initialize the database
	@app.before_first_request
	def initialize_database():
		Database.initialize()

	#this is the route to rest password
	@app.route(Tenplates.rest('/rest'))
	def forget():
		return render_templates(Templates.restpass("restpass.html"))

	#this is the route to rest password
	@app.route(Templates.HOME_ROUTER('/'))
	def home():
		return render_templates(Templates.homeIndex("index.html"))
	#this is the route for the login 
	@app.route(Templates.LOGIN_ROUTER('/login'))
	def login():
		return render_templates(Templates.log_in("login.html"))

	#this is the route for sigup
	@app.route(Templates.SIGNUP_ROUTER('/signup'))
	def signup():
		return render_template(Templates("signup.html"))
	#this is the route  for upload
	@app.route('/uploads/<filename>')
	def uploaded_file(filename):
		return send_from_directory(app.config['UPLOAD_FOLDER'],filename)

	#signup end point
	@app.route(Templates.ftp_ROUTER('/ftp'))
	def ftp():
		return render_template("ftp.html")
	#thisis is the route for the 
	@app.route(Templates.login_url_router('/auth/login/'),Templates.login_post_router(methods=['POST','GET']))
	def login_user():
		error = None

		if request.method == 'POST':
			email =  request.form['email']
			password = request.form['password']

			if Users.login_valid(request.form['email'],request.form['password']):
					user = Users.login(email)
					img  = File_system.image(email)

					flash("you have Succesfuly logged in")
					response = make_response(redirect(url_for('welcome',email=request.form.get('email'),image=img['image'],id=img['_id'])))
					response.set_cookie('email',request.form.get('email'))
					return  response


			else:
					error = 'User'+" "+ request.form['email']+" "+'does not exist'
					session['email'] =  None
					return render_template("login.html",error=error)

		return render_template("profile.html", email=request.form.get('email'))

	@app.route(Templates.url('/auth/ftp/'),Templates.urlr(methods=['POST','GET']))
	def ftps():
		if request.method == 'POST':
			email =  request.form['email']
			password = request.form['password']
			reg = Userss(email,password,"nopicture")
			mail = reg.get_by_email(email)
			if mail is None:
				reg.registration(request.form['email'],request.form['password'],"ithollie")
			else:
				return redirect(url_for('loginend_point'))
		return render_template("download.html")
	#logout router
	@app.route(Templates.Logout('/logout'))
	def logout():
		response = make_response(redirect(url_for('login')))
		response.set_cookie('email_set', '', expires=0)
		return response

	def allowed_file(filename):
		return '.' in filename and filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']

	@app.route('/welcome/<string:email>/<image>/<id>')
	def welcome(email,image,id):
		make_cook = request.cookies.get('email')
		if make_cook is not None:
			return render_template('portfolio.html',email=email,image=image)
		else:
			return redirect(url_for('loginend_point'))
	#reg router
	@app.route(Templates.Reg('/auth/signup'), Templates.Reg(methods=['POST','GET']))
	def register_user():
		name = request.form['name']
		lastname = request.form['lastname']
		email =  request.form['email']
		password = request.form['password']
		phote = request.files['file']


		if phote and allowed_file(phote.filename):
			    # Make the filename safe, remove unsupported chars
			filename = secure_filename(phote.filename)
			    # Move the file form the temporal folder to
			    # the upload folder we setup
			if not os.path.exists(fullpath):
				#The folder to send the file if something is goes wrong
				PATH  ='C:\\Users\hacker\desktop\startup\machine\Assets\empyt_folder'
				#config path folder
				app.config['UPLOAD_FOLD'] = PATH
				#changing dir
				os.chdir('C:\\users\hacker\desktop\startup\machine\static\Assets')
				# make a new folder
				os.mkdir("empyt_folder")
				file_name =  secure_filename(phote.filename)
				phote.save(os.path.join(app.config['UPLOAD_FOLD'],file_name))
				Users.registration(reguest.form['name'], request.form['lastname'], equest.form['email'],request.form['password'],filename)
			else:
				filename =  secure_filename(phote.filename)
				phote.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
				Users.registration(request.form['name'] ,request.form['lastname'],request.form['email'],request.form['password'],filename)
			#return redirect(url_for('uploaded_file',filename=filename))
		return redirect(url_for(Templates.elslogin('login')))
예제 #32
0
	def signup():
		return render_template(Templates("signup.html"))
예제 #33
0
	def login():
		return render_templates(Templates.log_in("login.html"))
예제 #34
0
	def home():
		return render_templates(Templates.homeIndex("index.html"))