Esempio n. 1
0
def add_member(title, descrip, picfile):
	"""
	Add a event to the database
	"""
	member = Member(name=title, desc=descrip,image=picfile)
	session.add(member)
	session.commit()
Esempio n. 2
0
    def get_member_set(self, condition = "is_traced = 1"):
        if condition:
            sql = "SELECT id, account, name, is_followed, is_traced, last_trace_time, favor from member where %s" % condition
        else:
            sql = "SELECT id, account, name, is_followed, is_traced, last_trace_time, favor from member"

        result = self.select(sql)
        member_set = []
        for item in result:
            member_set.append(Member(id = item[0], account = item[1], name = item[2], is_followed = item[3], is_traced = item[4], last_trace_time = item[5], favor = item[6]))

        return member_set
Esempio n. 3
0
    def post(self):
        if self.request.get('store') != '1':
            self.redirect('/members')
            return

        try:
            member = Member()
            member.name = self.get_var('name')
            member.address = self.get_var('address')
            member.zipcode = self.get_var('zip')
            member.city = self.get_var('city')
            member.country = Country.get(self.get_var('country'))
            member.email = self.get_var('email', optional=True)
            member.mobile = self.get_var('mobile', optional=True)
            member.home = self.get_var('home', optional=True)
            member.work = self.get_var('work', optional=True)
            member.membertype = MemberType.get(self.get_var('type'))
            member.notes = self.get_var('comment', optional=True)
            member.status = Status.get(self.get_var('status'))
            member.number = dbutils.create_new_member_no()
            member.member_since = datetime.date.today()
            member.generate_access_code()
            mcount = self.get_var('magazine_count', optional=True)
            member.magazine_count = int(mcount) if mcount else 1
            member.put()
            self.redirect('/members/%s/edit' % member.key())
            return
        except MissingField:
            # TODO: Redirect
            template = JINJA_ENVIRONMENT.get_template(
                'templates/members/new_member.html')
            countries = Country.all().order('order').fetch(LIMIT)
            statuses = Status.all().order('order').fetch(LIMIT)
            types = MemberType.all().order('order').fetch(LIMIT)
            data = {}
            for name in [
                    'name', 'address', 'zip', 'country', 'email', 'mobile',
                    'home', 'work', 'type', 'comment', 'status'
            ]:
                data[name] = self.request.get(name)

            params = {
                'countries': countries,
                'statuses': statuses,
                'types': types,
                'data': data
            }
            self.response.write(template.render(params))
            return

        self.redirect('/members')
Esempio n. 4
0
def member_update():
    """Member updation process"""

    first_name = request.form.get("Member_Firstname")
    last_name = request.form.get("Member_Lastname")
    email = request.form.get("Member_Email")
    phonenumber = request.form.get("Member_Phonenumber")
    date_of_birth_str = request.form.get("Member_Birthday")
    date_of_birth = datetime.strptime(date_of_birth_str, '%Y-%m-%d')
    marriage_date_str = request.form.get("Member_Marriage_Anniversary")
    if marriage_date_str != '':
        marriage_date = datetime.strptime(marriage_date_str, '%Y-%m-%d')
    else:
        marriage_date = None

    relation = request.form.get("Member_Relation")

    user_profile = get_profile()

    member_profile = Member(profile_id=user_profile.profile_id,
                            first_name=first_name,
                            last_name=last_name,
                            email=email,
                            phonenumber=phonenumber,
                            date_of_birth=date_of_birth,
                            marriage_date=marriage_date,
                            relation=relation)
    db.session.add(member_profile)
    db.session.commit()

    #Add birthday and marriage anniversary to events
    text = f"Birthday for {first_name} {last_name}"
    member_db_event = Event(profile_id=user_profile.profile_id,
                            member_id=member_profile.member_id,
                            event_type='Birthday',
                            event_date=date_of_birth,
                            event_text=text)
    db.session.add(member_db_event)
    if marriage_date is not None:
        text = f"Marriage Anniversary for {first_name} {last_name} and {user_profile.fullname()}"
        marriage_event = Event(profile_id=user_profile.profile_id,
                               member_id=member_profile.member_id,
                               event_type='Marriage_Anniversary',
                               event_date=marriage_date,
                               event_text=text)
        db.session.add(marriage_event)
    db.session.commit()
    return redirect("/member")
Esempio n. 5
0
    def fetch_following(self,
                        restrict="public",
                        page_count=sys.maxsize,
                        start_id=None):
        cur_offset = start_id
        count = 0
        while cur_offset != "END" and count < page_count:
            count += 1

            member_list = []
            result = self.api.user_following(self.userid,
                                             restrict=restrict,
                                             offset=cur_offset,
                                             req_auth=True)

            if result.next_url is None:
                cur_offset = "END"
            else:
                cur_offset = int(
                    urllib.parse.parse_qs(
                        urllib.parse.urlparse(
                            result.next_url).query)['offset'][0])

            print("count: %d, cur_offset: %s" % (count, str(cur_offset)))

            for user_preview in result.user_previews:
                # print(user_preview.illusts)
                user = user_preview.user
                member = Member(user.id,
                                user.account,
                                user.name,
                                is_followed=True,
                                favor=1)
                member_list.append(member)

            if not self.store.handle_members_follow(member_list):
                # log
                print(
                    "fetch following fail because of insert members error. Members info"
                )
                for member in member_list:
                    print(member.id + " " + member.name)
                print(
                    "-------------------------------------------------------------------"
                )
Esempio n. 6
0
 def post(self):
     req_user = self.request.user
     gu_obj = GoogleUser.get_or_insert(req_user.user_id())
     if gu_obj.name:
         self.redirect('/')
         return
     
     errors = []
     name = self.POST['name'].strip().lower()
     if name:
         if len(name)<20:
             if re.search('^[a-zA-Z0-9]+$', name):
                 check_obj = Member.get_by_key_name(str(name))
                 if check_obj:
                     errors.append('该用户名已被注册,请换一个吧')
                 else:
                     #get member id
                     mid_obj = Counter.get_or_insert('member_auto_increment',name = 'member_auto_increment', value = 1)
                     nuser_obj = Member(key_name=name, id = mid_obj.value, flag = 1, add = int(time()))
                     nuser_obj.put()
                     if nuser_obj.is_saved():
                         #set google user
                         gu_obj.name = name
                         db.run_in_transaction(obj_runput,gu_obj)
                         #all member num +1
                         mid_obj.value += 1
                         db.run_in_transaction(obj_runput,mid_obj)
                         self.redirect('/setavatar')
                         return
                     else:
                         errors.append('服务器出现意外错误,请稍后再试')
             else:
                 errors.append('用户名只能包含字母和数字')
         else:
             errors.append('用户名太长了')
     else:
         errors.append('用户名必填')
     
     self.echo('setname.html', {
         'title': "设置名字",
         'errors':errors,
         'name':name,
         'newest_node': Node.get_newest(),
     }, layout='_layout.html')
Esempio n. 7
0
def task_member_restore(items):

    for item in items:
        member = Member()
        member.number = item['number']
        member.address = item['address']
        if item['email'] != '' and item['email'] != None:
            member.email = db.Email(item['email'])
        member.name = item['name']
        member.member_since = string_to_date(item['memberSince'])
        if item['phone'] != '' and item['phone'] != None:
            member.phone = db.PhoneNumber(item['phone'])
        if item['phoneWork'] != '' and item['phoneWork'] != None:
            member.phone_work = item['phoneWork']
        if item['phoneHome'] != '' and item['phoneHome'] != None:
            member.phone_home = item['phoneHome']
        member.notes = item['notes']
        member.zipcode = item['zipcode']
        member.city = item['city']
        member.county = item['county']
        member.country = db.get(db.Key.from_path('Country', item['countryId']))
        member.status = db.get(db.Key.from_path('Status', item['statusId']))
        member.membertype = db.get(
            db.Key.from_path('MemberType', item['typeId']))
        member.put()

        for itemdue in item['membershipDues']:
            due = MembershipDues(parent=member,
                                 year=itemdue['year'],
                                 paid=itemdue['paid'])
            due.put()

        for itemcar in item['cars']:
            car = Car()
            car.member = member
            car.registration = itemcar['registration']
            car.model = db.get(db.Key.from_path('CarModel',
                                                itemcar['modelId']))
            car.bought_year = itemcar['boughtYear']
            car.sold_year = itemcar['soldYear']
            car.year = itemcar['year']
            car.notes = itemcar['notes']
            car.serial_no = itemcar['serialNo']
            car.put()
Esempio n. 8
0
def auth_session(request: Request):
    token = oauth.fetch_token(
        'https://accounts.google.com/o/oauth2/token',
        authorization_response=str(request.url),
        # Google specific extra parameter used for client
        # authentication
        client_secret=client_secret)

    header = jwt.get_unverified_header(token['id_token'])

    cert_str = requests.get('https://www.googleapis.com/oauth2/v1/certs').json(
    )[header['kid']].encode()
    cert_obj = load_pem_x509_certificate(cert_str)
    pub_key = cert_obj.public_key()

    payload = jwt.decode(token['id_token'],
                         pub_key,
                         algorithms=['RS256'],
                         audience=client_id)

    if payload['iat'] - 60 < time.time() < payload['exp']:
        if payload['email_verified']:
            response = RedirectResponse('/shop/goods/#')

            id_ = payload['sub']

            user = session.query(Member).filter(Member.id == id_).first()

            if not user:
                session.add(Member(id=id_, email=payload['email']))
                session.commit()

            response.set_cookie('kw_id', id_, max_age=token['expires_in'])
            return response
        else:
            raise jwt.PyJWTError('email_verified must be true')
    else:
        raise jwt.PyJWTError(
            f'this token is invalid at present {payload["iat"]} < {time.time()} < {payload["exp"]}'
        )
Esempio n. 9
0
    def parse_bookmark(self, bookmark_json):
        member = Member(bookmark_json.user.id,
                        bookmark_json.user.account,
                        bookmark_json.user.name,
                        favor=1)
        # print(bookmark_json)

        if bookmark_json.page_count == 1:
            first_url = bookmark_json.meta_single_page.original_image_url.strip(
            )
        else:
            first_url = bookmark_json.meta_pages[0].image_urls.original.strip()

        if "limit" in first_url:
            url_template = first_url
        elif bookmark_json.type == "ugoira":
            url_template = first_url.split(
                "ugoira")[0] + "ugoira%d." + first_url[-3:]
        else:
            url_template = first_url.split("_p")[0] + "_p%d." + first_url[-3:]

        illust = Illust(bookmark_json.id,
                        bookmark_json.user.id,
                        bookmark_json.title,
                        bookmark_json.type,
                        bookmark_json.page_count,
                        bookmark_json.create_date,
                        url_template,
                        bookmark_json.sanity_level,
                        bookmark_json.caption,
                        favor=0,
                        book=True)

        tag_set = set()
        for tag in bookmark_json.tags:
            tag_set.add(tag.name)

        return member, illust, tag_set
Esempio n. 10
0
    def get(self):
        config = Configuration()
        ruler = """
--------------------------------------------------------------------------------
0________1_________2_________3_________4_________5_________6_________7_________8
1        0         0         0         0         0         0         0         0
--------------------------------------------------------------------------------
"""
        template = Template(config.get('WELCOME_MAIL_TEXT'))

        member = Member()
        member.name = 'Ola Normann'
        member.address = 'Norskeveien 1'
        member.zipcode = '9876'
        member.city = 'Olabyen'
        member.country = Country().all().order('order').fetch(1)[0]
        member.email = '*****@*****.**'
        member.phone = '916 75 105'
        member.phone_home = '939 90 115'
        member.phone_work = '101 33 116'
        member.number = '9669'
        member.access_code = 'BBQWTF'
        member.member_type = MemberType.all().order('order').fetch(1)[0]
        sample_data = {
            'year': 2014,
            'fee': 400,
            'account_no': config.get('GIRO_ACCOUNT_NO'),
            'member': member,
            'profile_url': constants.PROFILE_URL
        }
        sample_text = template.render(sample_data)
        # Merge template before submitting text
        data = {'text': ruler + sample_text + ruler}

        template = JINJA_ENVIRONMENT.get_template(
            'templates/settings/email_preview.html')
        self.response.write(template.render(data))
Esempio n. 11
0
    def post(self):
        complete = []
        incomplete = []
        values = {}

        # Holy crap this is ugly. There has to be a better way.

        name = self.request.get('name')
        if not name or name.strip() == '' or name.strip().startswith('http'):
            incomplete.append('name')
        else:
            values['name'] = name
            complete.append('name')

        address = self.request.get('address')
        # Spammers put URLs in the address field so we reject those right away
        if not address or address.strip() == '' or address.strip().startswith(
                'http'):
            incomplete.append('address')
        else:
            values['address'] = address
            complete.append('address')

        zipcode = self.request.get('zip')
        if (not zipcode or zipcode.strip() == '') or len(zipcode.strip()) < 4:
            incomplete.append('zip')
        else:
            values['zip'] = zipcode
            complete.append('zip')

        city = self.request.get('city')
        if not city or city.strip() == '':
            incomplete.append('city')
        else:
            values['city'] = city
            complete.append('city')

        if 'zip' in incomplete or 'city' in incomplete:
            incomplete.append('zipcity')

        country_key = self.request.get('country').strip()
        country = Country.get(country_key)

        countries = Country.all().order('order').fetch(100)

        if not country or not country_key or country_key.strip() == '':
            incomplete.append('country')
            # retrieve countries since we're going to need them
        else:
            values['country'] = country.name
            complete.append('country')

        email = self.request.get('email')
        if not email or email.strip() == '' or not mail.is_email_valid(email):
            incomplete.append('email')
        else:
            values['email'] = email
            complete.append('email')

        mobile = self.request.get('mobile')
        if mobile and mobile.strip() == '':
            mobile = None
        values['mobile'] = mobile

        home = self.request.get('home')
        if home and home.strip() == '':
            home = None
        values['home'] = home

        work = self.request.get('work')
        if work and work.strip() == '':
            work = None
        values['work'] = work

        member_type = self.request.get('type')
        if not member_type or member_type.strip() == '':
            member_type = '1'

        types = MemberType.all().fetch(100)

        mtype = None

        # TODO: Custom settings? Constants at least.
        if member_type == '1':
            mtype = next(t for t in types if t.name == DEFAULT_MEMBER_NAME)
        else:
            mtype = next(t for t in types
                         if t.name == DEFAULT_SUPPORT_MEMBER_NAME)

        values['type'] = mtype.name
        comment = self.request.get('comment')
        complete.append('comment')
        values['comment'] = comment

        error_message = ''

        # Check if member exists;
        existing = Member.all().filter('email', email).fetch(1)

        if len(existing) > 0:
            incomplete.append('email')
            error_message = 'Det er allerede registrert noen i medlemsregisteret med denne epostadressen!'
            # TODO: Error message

        if len(incomplete) > 0:
            # missing field, redirect to signup page again
            template = JINJA_ENVIRONMENT.get_template(
                'templates/selfservice/signup.html')
            return self.response.write(
                template.render({
                    'countries': countries,
                    'incomplete': incomplete,
                    'complete': complete,
                    'error_message': error_message,
                    'values': values
                }))

        # invariant: fields are OK, create new member, send mail,
        # create payment history on member.
        template = JINJA_ENVIRONMENT.get_template(
            'templates/selfservice/signup_receipt.html')
        data = {'values': values, 'profile_url': PROFILE_URL}

        statuses = Status.all().fetch(100)

        # TODO: Handle existing members signing up again

        new_member = Member()

        new_member.name = name
        new_member.address = address
        new_member.zipcode = zipcode
        new_member.city = city
        new_member.notes = comment
        new_member.country = country
        new_member.membertype = mtype

        status = next(s for s in statuses if s.name == SIGNUP_STATUS_NAME)
        new_member.status = status

        new_member.number = dbutils.create_new_member_no()

        new_member.email = email
        new_member.member_since = datetime.date.today()
        if mobile:
            new_member.phone = mobile
        if work:
            new_member.phone_work = work
        if home:
            new_member.phone_home = home
        new_member.generate_access_code()
        new_member.member_since = datetime.date.today()
        new_member.member_type = mtype
        new_member.put()
        new_member.update_index()

        self.send_welcome_mail(new_member)
        self.send_notification_mails(new_member)

        # TODO: Invalidate counts for categories
        # Handle mutations on members gracefully

        return self.response.write(template.render(data))
Esempio n. 12
0
def add_Member(name_input, pwd_input):
    member_object = Member(Name=name_input, Password=pwd_input)
    session.add(member_object)
    session.commit()
Esempio n. 13
0
#!/usr/bin/env python

import arrow
import yaml
from sqlalchemy import and_, or_

from crud import Session, create_database, drop_database, recreate_database
from model import Case, Member, CaseDetermination

recreate_database()
s = Session()

member = Member(client_id="abc", external_member_id="123", person_code="01")
s.add(member)

s.commit()

case0 = Case(
    case_number=1000000000,
    rn="rn0",
    drug_ndc="drug_ndc0",
    origin="fax",
    member_id=member.id,
    prescriber_npi="0123456789",
    requester_type="pharmacy",
)
s.add(case0)

case1 = Case(
    case_number=1000000001,
    rn="rn1",
Esempio n. 14
0
    def post(self):
        req_user = self.request.user
        gu_obj = GoogleUser.get_or_insert(req_user.email())
        if gu_obj.name:
            self.redirect('/')
            return

        errors = []
        name = self.POST['name'].strip().lower()
        if name:
            if len(name) < 20:
                if re.search('^[a-zA-Z0-9]+$', name):
                    check_obj = Member.get_by_key_name(str(name))
                    if check_obj:
                        errors.append('该用户名已被注册,请换一个吧')
                    else:
                        #get member id
                        mid_obj = Counter.get_or_insert(
                            'member_auto_increment',
                            name='member_auto_increment',
                            value=1)
                        nuser_obj = Member(key_name=name,
                                           id=mid_obj.value,
                                           flag=1,
                                           add=int(time()))
                        nuser_obj.put()
                        if nuser_obj.is_saved():
                            #set google user
                            gu_obj.name = name
                            db.run_in_transaction(obj_runput, gu_obj)
                            #all member num +1
                            mid_obj.value += 1
                            db.run_in_transaction(obj_runput, mid_obj)

                            #try to Fetch Google Plus Profile Picture
                            try:
                                img_url = 'https://profiles.google.com/s2/photos/profile/' + req_user.nickname(
                                )
                                img_data = read_img(img_url)
                                #self.header['Content-Type'] = "image/jpg"
                                if img_data:
                                    pass
                                else:
                                    img_url = 'https://www.gravatar.com/avatar/%s?s=73&d=monsterid' % md5(
                                        req_user.email()).hexdigest()
                                    img_data = read_img(img_url)

                                if img_data:
                                    imgobj = images.Image(img_data)
                                    if imgobj.width <= 73 and imgobj.height <= 73:
                                        img_large = img_data
                                    else:
                                        imgobj.resize(73, 73)
                                        imgobj.im_feeling_lucky()
                                        img_large = imgobj.execute_transforms(
                                            output_encoding=images.JPEG,
                                            quality=95)

                                    u = UpYun(DOMAIN_NAME_AVATAR, UPYUN_USER,
                                              UPYUN_PW)
                                    file_path_name = '/avatar/%s.jpg' % self.cur_user.name
                                    avatar = u.writeFile(
                                        file_path_name, img_large, True)

                                    if avatar:
                                        m_obj = self.cur_user  #Member.get_by_key_name(self.cur_user.name)
                                        if m_obj.flag == 1:
                                            if m_obj.id == 1:
                                                m_obj.flag = 99
                                            else:
                                                m_obj.flag = 2
                                            db.run_in_transaction(
                                                obj_runput, m_obj, [
                                                    'cur_user:'******'Fetch Google Plus Profile Picture Failure: '
                                    + req_user.email())
                            #
                            self.redirect('/setavatar')
                            return
                        else:
                            errors.append('服务器出现意外错误,请稍后再试')
                else:
                    errors.append('用户名只能包含字母和数字')
            else:
                errors.append('用户名太长了')
        else:
            errors.append('用户名必填')

        self.echo('setname.html', {
            'title': "设置名字",
            'errors': errors,
            'name': name,
            'newest_node': Node.get_newest(),
        },
                  layout='_layout.html')
Esempio n. 15
0
    def import_members(self, member_csv):
        member_csv = member_csv.split('\n')
        lines = self.unmangle(member_csv)

        count = 0
        for fields in lines:
            #fields.reverse()
            print '-' * 80
            print fields
            print '=' * 80
            fields.reverse()
            member = Member()

            (fee2009, fee2010, fee2011, fee2012,
             fee2013, fee2014) = (fields.pop(), fields.pop(), fields.pop(),
                                  fields.pop(), fields.pop(), fields.pop())

            member.address = fields.pop()
            # Skip the cars
            for carno in range(1, 6):
                (car, registration) = (fields.pop(), fields.pop())

            email = fields.pop()
            if email != '':
                member.email = db.Email(email)

            (lastname, firstname) = (fields.pop(), fields.pop())
            full_name = firstname + ' ' + lastname
            member.name = full_name.strip()

            member.county = fields.pop().strip()
            member_since = fields.pop()
            date = self.string_to_date(member_since)
            if date:
                member.member_since = date
            else:
                print 'Error converting date from', member_since

            country = fields.pop().strip()
            if country == '':
                country = 'Norge'
            member.country = self.string_to_country(country)
            member.membertype = self.string_to_type(fields.pop())
            member.number = fields.pop()
            mobile = fields.pop()
            if mobile != '':
                member.phone = db.PhoneNumber(mobile)

            member.notes = fields.pop()
            member.zipcode = fields.pop()
            member.city = fields.pop()
            work = fields.pop()
            home = fields.pop()
            if work != '':
                member.phone_work = db.PhoneNumber(work)
            if home != '':
                member.phone_home = db.PhoneNumber(home)
            member.status = self.get_status('Medlem')
            member.generate_access_code()
            member.put()

            self.add_due(member, 2009, fee2009 == 'Betalt')
            self.add_due(member, 2010, fee2010 == 'Betalt')
            self.add_due(member, 2011, fee2011 == 'Betalt')
            self.add_due(member, 2012, fee2012 == 'Betalt')
            self.add_due(member, 2013, fee2013 == 'Betalt')
            self.add_due(member, 2014, fee2014 == 'Betalt')
            count = count + 1

        print 'Imported', count, 'members'