def post(uid,n):
    user = getUser(n["uid"])
    thread = getThread(n['tid'])
    n["username"] = user["username"]
    n["date"] = n["date"].strftime(DATE_FORMAT)

    n['className'] = "active"
    show = True
    if not n['hid'] or admin(uid):
        n["content"] = "<br />".join(cgi.escape(n["content"]).split("\n"))
    else:
        show = False
        n["content"] = "This post has been hidden by an administrator."
    if n['hid']:
        n['className'] = "danger"

    # allow editing abilities
    n['pleft'] = ""
    if uid == n["uid"] or admin(uid):
        n['pleft'] = '<a href="/editpost-%d" class="btn btn-primary">Edit</a>'%(n['id'])

    # admin buttons
    if admin(uid):
        # if it isn't the first post

         #   n['pleft'] += ' &nbsp; <a href="/delpost-%d" class="btn btn-danger">Delete</a>'%(n['id'])
#            n['pleft'] += '<br /><br /><a href="#">Hide</a> &nbsp; &nbsp; <a href="#">Delete</a>'
        if n['hid']:
            n['pleft'] += ' <a href="unhidepost-%d" class="btn btn-warning">Unhide</a>'%(n['id'])
        else:
            n['pleft'] += ' <a href="hidepost-%d" class="btn btn-warning">Hide</a>'%(n['id'])
        if n['id'] != thread['pid']:
            n['pleft'] += ' <a href="/delpost-%d" class="btn btn-danger deletePost">Delete</a>'%(n['id'])


    # show last post edit time
    if "editdate" in n.keys():
        n['editdate'] = " - Lasted edited on %s"%(n["editdate"].strftime(DATE_FORMAT))
        if n["edituid"] != n["uid"]:
            n['editdate'] += " by <strong>%s</strong>"%(getUser(n['edituid'])['username'])
    else:
        n['editdate'] = ""

    r = """
<table class="table p_post" cellspacing="0">
<tr class="%(className)s">
<td class="p_left">"""%(n)
    if show:
        r += '<div class="user"><a href="user/%(uid)d">%(username)s</a></div><div class="p_buttons">%(pleft)s</div>'%(n)
    r += """</td>
<td class="p_right"><div class="p_date">%(date)s %(editdate)s</div><div class="p_content">%(content)s</div></td>
</tr>
</table>"""%(n)
    

    return r
    def _getProfileFromUser(self):
        """Return user Profile from DataStore or create add new one if
        non-existent."""

        # Getting and Verifying current user
        user = getUser()
        
        # get the user_id (email) 
        user_id = getUserId(user)

        # Creating a profile key. 
        p_key = ndb.Key(Profile, user_id)
        
        # Using the profile key to get a profile Object
        profile = p_key.get()

        # create new Profile if not there
        if not profile:
            
            profile=Profile(
                key=p_key,
                displayName=user.nickname(),
                mainEmail=user.email(),
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),)
            
            profile.put()
        
        return profile 
    def getConferenceSessions(self, request):
        """Given a conference, return all sessions."""
        
        # Getting and Verifying current user
        user = getUser()
        
        # Retrieve the Conference key
        try:
            c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        except Exception:
            raise endpoints.BadRequestException(
                'The websafeConferenceKey given is invalid.')
        
        # Verify that the Conference exists
        conf = c_key.get()
        
        checkObj(conf, 'Conference')

        # Store Sessions that are ancestors
        sessions = Session.query(ancestor=c_key)
        
        # Return a SessionForm for each Session
        return SessionForms(
            items = [self._copyConferenceSessionToForm(
                sess) for sess in sessions])
    def _createSpeakerObject(self, request):
        """Create a Speaker object, returning SpeakerForm/request."""
        
        # Getting and Verifying current user
        user = getUser()

        # Confirm the field is filled out
        checkField(request.name, 'name')

        # Copy SpeakerForm/ProtoRPC Message into dict
        data = ({field.name: getattr(request, field.name)
                for field in request.all_fields()})

        # Create a key for the Speaker
        s_id  = Session.allocate_ids(size=1)[0]
        s_key = ndb.Key(Speaker, s_id)
        
        # Update stored session with session keys
        data['key'] = s_key
        
        # Create and update session and return the form
        Speaker(**data).put()
        
        taskqueue.add(
        
            params = {
                'email'   : user.email(),
                'subject' : 'You Added %s as a Speaker!' % data['name'],
                'body'    : 'Here are the details for the added speaker:',
                'info'    : repr(request)},
        
            url    = '/tasks/send_confirmation_email')
        
        return request
def getHeader(uid):
    if uid == -1:
        return '''
<nav class="navbar navbar-default">
<div class="navbar-header">
<a class="navbar-brand" href="/">Home</a>
<ul class="nav navbar-nav">
<li class="active"><a href="login">Login</a></li>
<li><a href="register">Register</a></li>
</ul>

</div>
</nav>
'''
    else:
        return '''
<nav class="navbar navbar-default">
<div class="navbar-header">
<a class="navbar-brand" href="/">Home</a>
<p class="navbar-text">Logged in as <strong>%s</strong></p>
<ul class="nav navbar-nav">
<li><a href="logout">Logout</a></li>
</ul>

</div>
</nav>
'''%(getUser(uid)["username"])
Exemple #6
0
def connect_db():
    _db = pymysql.connect(utils.getHost(),
                          utils.getUser(),
                          utils.getPwd(),
                          utils.getDb(),
                          use_unicode=True,
                          charset="utf8")
    cursor = _db.cursor()
    return cursor
Exemple #7
0
def callback():
    from jahresdatenprovider import JahresdatenProvider
    import utils

    prov = JahresdatenProvider()
    prov.connect(utils.getUser())
    l: List[JahresdatenCollection] = prov.getJahresdaten(1, 2018, 2020)
    global g_jv
    g_jv.setValues(l)
    def getFeaturedSpeaker(self, request):
        """Return Featured Speaker from memcache."""

        # Getting and Verifying current user
        user = getUser()
        
        # return an existing Featured Speaker from Memcache or an empty string.
        featured = memcache.get(MEMCACHE_FEATURED_SPEAKER_KEY)
        if not featured:
            featured = ""
        return StringMessage(data=featured)
Exemple #9
0
 def __init__(self,
              host=utils.getHost(),
              user=utils.getUser(),
              pwd=utils.getPwd(),
              db_name=utils.getDb()):
     self._db = pymysql.connect(host,
                                user,
                                pwd,
                                db_name,
                                use_unicode=True,
                                charset="utf8")
     self.cursor = self._db.cursor()
Exemple #10
0
def push(doc_id=False, path=False, comment=False, vtype="review", **kwargs):
    """
    This function copy the desired file from local workspace to repository.

    :param doc_id: The asset code
    :type doc_id: str
    :param path: The list of files to push
    :type path: str/list of str
    :param comment: This is the comment of the push
    :type comment: str
    :param vtype: Version type *review/release*
    :type vtype: str
    :returns: str -- Return the published directory

    **Example:**
    >>> path="/homeworks/users/jdoe/projects/bls/chr/mimi/mod/a/file.mb"
    >>> push(doc_id="bls_chr_mimi_mod_a", path=path, comment="my comments")
    """

    if not all([path, doc_id, comment, vtype]):        # Check arguments
        print("pushfile(): wrong arguments.")
        return False

    def getAssetRepo(path, doc_id):
        if os.path.isdir(path):
            return doc_id
        ext = os.path.splitext(path)[-1]                # Get file extension
        return doc_id + ext

    stat = dict()
    db = getDb()                                        # Get DB
    doc = db[doc_id]                                    # Get asset document
    ver_attr = getVersions(db, doc_id, vtype=vtype)     # Get versions document
    stat["version"] = len(ver_attr) + 1
    repo = getPathFromId(doc_id, vtype=vtype)           # Get asset repo
    name = getAssetRepo(path, doc_id)                   # Get name
    ver = "%04d" % stat["version"]                      # Get last version num
    stat['target'] = os.path.join(repo, ver, name)      # Target

    # Create the version data for "versions" document's attribute
    fileinfo = dict()
    fileinfo["creator"] = utils.getUser()
    fileinfo["created"] = time.time()
    fileinfo["comment"] = comment
    fileinfo["release"] = list()
    fileinfo["path"] = stat['target']
    fileinfo["stat"] = False
    ver_attr[stat["version"]] = fileinfo
    stat["pubinfo"] = fileinfo
    doc[vtype] = ver_attr
    db[doc_id] = doc
    return stat  # Return the path to publish data
    def getSpeakersByConference(self, request):
        """Given a websafeConferenceKey, return all speakers."""
        
        # Getting and Verifying current user
        user = getUser()

        # Retrieve the Conference key
        try:
            
            c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        
        except Exception:
        
            raise endpoints.BadRequestException(
                'The websafeConferenceKey is invalid.')
        
        # Verify that the conference exists
        conference = c_key.get()

        checkObj(conference, 'Conference')

        # Save the ancestors the Conference obj
        sessions = Session.query(ancestor=c_key)
        
        # Retrieve Speaker Keys from each Session in a Conference
        speakerKeys = set()

        for sess in sessions:
            
            for webSafeKey in sess.speakerKey:
                
                speaker_key = ndb.Key(urlsafe=webSafeKey)
                
                # add to set
                speakerKeys.add(speaker_key)

        # Container to keep speaker objects
        speakers = []
        
        # Get each speaker and add to the set
        for spk in speakerKeys:
            
            speaker = spk.get()

            speakers.append(speaker)

        # Return one or many SpeakerForms for Speakers
        return SpeakerForms(
            items = [self._copySpeakerToForm(
                spkr) for spkr in speakers])
Exemple #12
0
  def listenChat(self):
    while True:
      try:
        self.readBuffer = self.readBuffer + (self.socket.recv(1024)).decode()
        temp = self.readBuffer.split("\r\n")
        self.readBuffer = temp.pop()
      except:
        print("Decode error.")

      for line in temp:
        user = getUser(line)
        message = getMessage(line)

        if user is not None and message is not None:
          self.listener(user, message, self.socket)
Exemple #13
0
def test():
    from tkinter import  Tk
    from tkinter import ttk
    import utils
    dp = JahresdatenProvider()
    dp.connect(utils.getUser())

    root = root = Tk()
    view = JahresdatenView(root)
    view.grid(column=0, row=0, sticky='nswe')
    ctrl = JahresdatenController(dp, view)
    ctrl.startWork()
    ctrl.wohnungSelected(1)

    root.mainloop()
    def _updateConferenceObject(self, request):
        """Update a Conference object, returning the updated ConferenceForm().
        """
        # Getting and Verifying current user
        user = getUser()

        # get the user_id (email) 
        user_id = getUserId(user)

        # copy data from ProtoRPC Message into dict
        data = ({field.name: getattr(request, field.name)
                for field in request.all_fields()})

        # update existing conference
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        
        # check that conference exists
        checkObj(conf, 'Conference')
        
        # To modify you must be the owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can modify the Conference.')

        # copy relevant fields from ConferenceForm to Conference object
        for field in request.all_fields():
            data = getattr(request, field.name)

            # only copy fields where we get data
            if data not in (None, []):
                
                # special handling for dates (convert string to Date)
                if field.name in ('startDate', 'endDate'):
                    
                    data = datetime.strptime(data, "%Y-%m-%d").date()
                    
                    if field.name == 'startDate':

                        conf.month = data.month
                
                # write to Conference object
                setattr(conf, field.name, data)
        
        conf.put()
        
        prof = ndb.Key(Profile, user_id).get()
        
        return self._copyConferenceToForm(conf, getattr(prof, 'displayName'))
    def getConferenceSessionsByType(self, request):
        """Given a conference and session type, return matching sessions."""
        
        # Confirm the user is authorized
        user = getUser()

        # First query for a session with specified key
        sessions = Session.query(
            ancestor=ndb.Key(urlsafe=request.websafeConferenceKey))
        
        # Second query for remaining Sessions by the type specified
        sessions = sessions.filter(
            Session.typeOfSession == request.typeOfSession)
        
        # Return a SessionForm for each Session
        return SessionForms(
            items = [self._copyConferenceSessionToForm(
                sess) for sess in sessions])
    def getConferencesCreated(self, request):
        """Return conferences created by user."""
        
        # Getting and Verifying current user
        user = getUser()

        # get the user_id (email) 
        user_id = getUserId(user)

        # create ancestor query for all key matches for this user
        conferences = Conference.query(ancestor=ndb.Key(Profile, user_id))
        
        prof = ndb.Key(Profile, user_id).get()
        
        # return one or many ConferenceForm objects
        return ConferenceForms(
            items = [self._copyConferenceToForm(
                conf, getattr(prof, 'displayName')) for conf in conferences])
Exemple #17
0
def release(db=None, doc_id=False, version=False, **kwargs):
    # TODO: Documentation for badass.core.release
    # Check if DB is provided else get the project DB
    if (not db) or db == "":
        db = getDb()

    doc = db[doc_id]  # Get document
    stat = dict()

    review = doc["review"]
    version = str(int(version))
    reviewVersion = review[version]
    if not ("release" in reviewVersion):
        reviewVersion["release"] = list()

    release = doc["release"]
    last = str(len(release) + 1)
    releaseVersion = dict()
    releaseVersion["comment"] = reviewVersion["comment"]
    releaseVersion["review"] = version
    releaseVersion["path"] = getPathFromId(doc_id=doc_id, vtype="release")
    releaseVersion["path"] = os.path.join(releaseVersion["path"], "%04d" %
                                          int(last))
    releaseVersion["created"] = time.time()
    releaseVersion["creator"] = utils.getUser()
    releaseVersion["stat"] = False
    release[last] = releaseVersion
    doc["release"] = release

    released = reviewVersion["release"]
    released.append(last)
    reviewVersion["release"] = released
    review[version] = reviewVersion
    doc["review"] = review

    src = reviewVersion["path"]
    dst = releaseVersion["path"]
    _id, _rev = db.save(doc)

    stat["version"] = last
    stat["source"] = src
    stat["target"] = dst
    return stat
Exemple #18
0
def sendmail_2():
    sub='美国江森自控安防系统产品资料' 
    html_content = '''<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=GB2312"></HEAD><BODY>
    <div class="gmail_quote"><div style="line-height:1.7;color:#000000;font-size:14px;font-family:arial">
    <div>您好!<br>&nbsp;&nbsp;美国江森自控安防系统产品请看附件!<br><br>&nbsp;</div>
    <div><div style="color:rgb(0,0,0);line-height:1.7;font-family:arial;font-size:14px">
    <div style="color:rgb(0,0,0);line-height:1.7;font-family:arial;font-size:14px"><div><div>
    <div>顺颂商祺!</div>
    <div>于卓琼</div>
    <div>市场总监</div>
    <div>T: 021-64512509&nbsp; C:13501693190&nbsp; E: <a href="mailto:[email protected]" target="_blank">[email protected]</a></div>
    <div><a href="http://blog.sina.com.cn/secsung" target="_blank">http://blog.sina.com.cn/secsung</a></div>
    <div>
    <div><span style="line-height:21px;font-family:Simsun">A more confortable, safe and sustainable world</span></div>
    <div>-----------------------------------------------<br style="line-height:21px;font-family:Simsun">
    <span style="line-height:21px;font-family:Simsun">江森自控上海总代理</span></div>
    <div><span style="line-height:21px;font-family:Simsun">19:24:09 2011-12-12</span></div></div></div></div></div></div>
    <div style="background:rgb(222,232,242);padding:4px;clear:both;font-family:verdana,Arial,Helvetica,sans-serif;margin-top:10px;margin-bottom:15px">
    <div style="padding:4px 8px 8px;line-height:16px;font-size:14px"><b>从网易163邮箱发来的超大附件</b></div><div style="background:rgb(255,255,255);padding:4px">
    <div style="padding:6px 4px;min-height:36px;clear:both">
    <div style="width:36px;float:left">
    <a href="http://fs.163.com/fs/display/?p=X-NETEASE-HUGE-ATTACHMENT&amp;file=Xt9C6OiQlThxcHl1OlqSAGfB6-TbYqzD4opBeoPvVB3BFOqda4CzUN7XQirmy137pNzMQzZJ8Zofu3eiHEgiTA&amp;title=%E6%B1%9F%E6%A3%AE%E8%B5%84%E6%96%99" target="_blank">
    <img src="cid:ico-bfile-6.gif"  border="0"></a></div>
    <div><div style="padding:0px;line-height:14px;font-size:12px">
    <a style="color:rgb(0,0,0);text-decoration:none" href="http://fs.163.com/fs/display/?p=X-NETEASE-HUGE-ATTACHMENT&amp;file=Xt9C6OiQlThxcHl1OlqSAGfB6-TbYqzD4opBeoPvVB3BFOqda4CzUN7XQirmy137pNzMQzZJ8Zofu3eiHEgiTA&amp;title=%E6%B1%9F%E6%A3%AE%E8%B5%84%E6%96%99" target="_blank">江森产品.rar</a>                                    <span style="color:rgb(187,187,187)"> (60.57M, 2011年12月27日 19:39 到期)</span> </div>
     <div style="padding:4px 0px;line-height:14px;font-size:12px"> <a href="http://fs.163.com/fs/display/?p=X-NETEASE-HUGE-ATTACHMENT&amp;file=Xt9C6OiQlThxcHl1OlqSAGfB6-TbYqzD4opBeoPvVB3BFOqda4CzUN7XQirmy137pNzMQzZJ8Zofu3eiHEgiTA&amp;title=%E6%B1%9F%E6%A3%AE%E8%B5%84%E6%96%99" target="_blank">下载</a>                                </div>
    </div></div></div></div>
    <br><br><span title="neteasefooter"><span></span></span></div></div><br><br><span title="neteasefooter"><span></span></span></div><br>
    </BODY></HTML>    ''' 
    mailto_list=utils.getMailList('maillist.txt')  
    userList = utils.getUser('mailuser.properties')
    userSize = len(userList)
    for to in mailto_list:
        user=userList[random.randint(0,userSize-1)];
        c_logger.info ( "%s start send %s" % (user.username,to))
        sendmail.send_mail( user.host , user.username , user.password ,  to, sub ,'' ,html_content,['ico-bfile-6.gif'])
        time.sleep(random.randint(1,3))
    c_logger.info( "finish")   
Exemple #19
0
def sendmail_1():
    sub='美国江森自控安防系统上海总代理-上海希宸经贸有限公司诚邀垂询' 
    html_content = '''<html><body>
    <b>详情请点击访问 <a 
    href='http://blog.sina.com.cn/secsung'>http://blog.sina.com.cn/secsung</a>
    <br><br>
    <img alt="" src="cid:johnson.jpg" style="border: none;" />
    详情请点击访问 <a 
    href='http://blog.sina.com.cn/secsung'>http://blog.sina.com.cn/secsung</a>
    <br><br><br><br></b>
    ------------------------------------------------<br>
    江森自控上海总代
    </body></html>
    ''' 
    mailto_list=utils.getMailList('maillist.txt')
    userList = utils.getUser('mailuser.properties')
    userSize = len(userList)
    for to in mailto_list:
        user=userList[random.randint(0,userSize-1)];
        c_logger.info ( "%s start send %s" % (user.username,to))
        sendmail.send_mail( user.host , user.username , user.password ,  to, sub ,'' ,html_content,['johnson.jpg'])
        time.sleep(random.randint(1,3))
    c_logger.info( "finish")   
Exemple #20
0
def lsProjectServer(serveradress):
    """
    This function return a list of all DbServer homeworks projects.

    :param serveradress: The database adress.
    :type serveradress: str
    :returns:  list -- Return the list of authorised project users.

    **Example:**

    >>> lsProjectServer ( serveradress = "admin:[email protected]:5984" )
    >>> [ 'prod1', 'prod2', 'prod3' ]
    """

    # Get db server from adress
    server = getServer(serveradress)
    projects = list()
    user = utils.getUser()

    # Iterate over all databases contained in the DB server
    for db_name in server:
        if db_name not in ("_replicator", "_users"):
            db = server[db_name]

            # Check if the current db is a BD project
            if isProject(db):

                # Get project authorized users
                users = getProjectUsers(db)

                # If current user is in the user list append project in the
                # project list
                if user in users:
                    projects.append(db_name)

    # Return a list of projects name (str)
    return projects
Exemple #21
0
def test():
    import sys

    print("path: ", sys.path)

    prov = JahresdatenProvider()
    prov.connect(utils.getUser())
    #l:List[JahresdatenCollection] = prov.getJahresdatenAlleWohnungen(2019, 2019)
    # l = prov.getJahresdaten(6, 2018, 2020)
    l = prov.getJahresdaten(6, 2018, 2020)

    root = Tk()
    #root.geometry('600x300')
    root.rowconfigure(0, weight=1)
    root.columnconfigure(0, weight=1)

    style = ttk.Style()
    style.theme_use('clam')

    jv = JahresdatenBaseView(root)
    jv.grid(column=0, row=0, sticky='nswe', padx=10, pady=10)
    jv.setValues(l)

    root.mainloop()
    def getConferencesByDate(self, request):
        """Given a Conference key and date return the associated Conference. 
        """
        
        # Getting and Verifying current user
        user = getUser()

        # get the user_id (email) 
        user_id = getUserId(user)

        conferences = Conference.query()

        # Convert the date string passed to a date Object
        date = datetime.strptime(request.date[:10], "%Y-%m-%d").date()

        # Get the Conferences
        conferences = conferences.filter(Conference.startDate == date)
        
        prof = ndb.Key(Profile, user_id).get()
        
        # return one or many ConferenceForm objects
        return ConferenceForms(
            items = [self._copyConferenceToForm(
                conf, getattr(prof, 'displayName')) for conf in conferences])
def thread(n,admin):
    r = ""
    if n['hid']:
        r += '<tr class="danger">'
        if not admin:
            r += '<td colspan="4">This thread has been hidden by an administrator.</td></tr>'
            return r
    elif n['lock']:
        r += '<tr class="warning">'
    else:
        r += '<tr class="active">'
    r += '<td class="t_name">'

    if "lock" in n.keys() and n['lock']:
        r += '<span class="glyphicon glyphicon-lock"></span> '

    r += '<a href="thread-%(id)d">%(title)s</a><div class="desc">%(desc)s</a></div></td>'%(n)
    r += '<td class="t_author"><a href="user-%(id)d">%(username)s</a></td>'%(getUser(n['uid']))
    r += '<td class="t_num">%d</td>'%(utils.threadPostCount(n['id']))
    
    a = utils.lastPostInfo(n['id'])
    r += '<td class="t_last"><a href="user-%d">%s</a><br />%s</td>'%(a['uid'],a['username'],a['date'].strftime(DATE_FORMAT))
    r += '</tr>'
    return r
    def _createSessionObject(self, request):
        """Create a Session object, returning SessionForm/request."""
        
        # Getting and Verifying current user
        user = getUser()

        # get the user_id (email) 
        user_id = getUserId(user)

        # Check that the 'name' field if filed
        checkField(request.name, 'name')

        # Check that the 'parentKey' field if filed
        checkField(request.parentKey, 'parentKey')
        
        # Attempt to retrieve the Conference or raise an exception
        try:
            _key = ndb.Key(urlsafe=request.parentKey)
        except Exception:
            raise endpoints.BadRequestException(
                'The parentKey given is invalid.')
        
        # Retrieve the Conference Obj 
        conf = _key.get()
        
        # Verify that the current user created the conference
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the conference creator can add a session to it.')
        
        # Check speakerKey and save them
        speakers = []
        
        if request.speakerKey:
        
            for speakerKey in request.speakerKey:
        
                try:
                    speaker = ndb.Key(urlsafe=speakerKey).get()
                    speakers.append(speaker)
        
                except Exception:
                    raise endpoints.BadRequestException(
                        'Check the speakerKey it is invalid.')
        
        # Copy SessionForm/ProtoRPC Message into dict
        data = ({field.name: getattr(request, field.name)
                for field in request.all_fields()})
        
        # If values not given for Session defaults, add defaults
        for df in SESSION_DEFAULTS:
        
            if data[df] in (None, []):
        
                data[df] = SESSION_DEFAULTS[df]
        
                setattr(request, df, SESSION_DEFAULTS[df])
        
        # Converting the date info from strings to Date objects
        # setting the object month to the start dates month
        if data['date']:
            data['date'] = (datetime.strptime(
                            data['date'][:10], "%Y-%m-%d").date())
            data['month'] = data['date'].month
        else:
            data['month'] = conf.month
        
        # Convert startTime from string to Time object
        if data['startTime']:
        
            data['startTime'] = (datetime.strptime(
                                 data['startTime'][:5], "%H:%M").time())
        
         # Convert typeOfSession to string
        if data['typeOfSession']:
        
            data['typeOfSession'] = str(data['typeOfSession'])
        
        # Create a session id for the Session,
        # create the relationship with parent key.
        s_id = Session.allocate_ids(size=1, parent=_key)[0]
        
        # Create the session key
        s_key = ndb.Key(Session, s_id, parent=_key)
        
        # Fill the session key
        data['key'] = s_key
        
        # Check that the speaker was passed
        if speakers:

            #  Query the session for instance of speakers 
            s = Session.query(
                ancestor=ndb.Key(urlsafe=request.parentKey))
            
            # Setting none as featured
            featured = None
            
            # Number of session
            instance_count = 0

            for spkr in data['speakerKey']:
                
                i_count = s.filter(Session.speakerKey == spkr).count()
                
                if i_count >= instance_count:
                
                    featured = spkr
                
                    minSessions = i_count

            # Advise of the featured Speaker using the taskQueue
            if featured:
                taskqueue.add(
                    params = {
                        'websafeConferenceKey': request.parentKey,
                        'websafeSpeakerKey'   : featured},
                    url    = '/tasks/set_featured_speaker',
                    method = 'GET')

        # Store in the DataStore
        Session(**data).put()
        
        # Send an email to the conference organizer
        taskqueue.add(
            params = {
                'email'   : user.email(),
                'subject' : 'You Created a New Session for %s!' % conf.name,
                'body'    : 'Here are the details for new Session:',
                'info'    : repr(request)},
            url    = '/tasks/send_confirmation_email')
        return request
Exemple #25
0
def createTask(db=None, doc_id="", comment="", overdoc=dict(), debug=False):
    """
    This function create a **task** into the provided database.

    :param db: The database.
    :type db: couchdb.client.Database
    :param doc_id: The asset code.
    :type doc_id: str
    :param comment: The asset comment.
    :type comment: str
    :param overdoc: A dictionnary that contains extra document attributes.
    :type overdoc: dict
    :returns:  document -- The database document.
    :raises: AttributeError, KeyError

    **Example:**

    >>> db = getDb(dbname="prod", serveradress="127.0.0.1:5984")
    >>> createTask(db=db, doc_id="prod_ch_mickey_mod_a", "modeling task 'a'")
    """

    # If 'db' isn't provided, get the current project database
    if db is None:
        db = getDb()

    # Get data from doc_id
    project, typ, slug, task, fork = doc_id.split("_")
    asset_id = "%s_%s_%s" % (project, typ, slug)
    asset = "%s_%s_%s_%s" % (typ, slug, task, fork)

    # Check if project name is right
    if not (project in db):
        print "createTask: %s project doesn't exist" % project
        return False

    # Check if the asset exist
    if not (asset_id in db):
        print "createTask: Asset '%s' doesn't exist" % asset_id
        return False

    # If task doesn't exist create it
    if doc_id in db:
        print "createTask: %s already exist" % asset
        return False

    # Create the task structure
    doc = {
        "_id": doc_id,
        "project": project,
        "type": typ,
        "name": slug,
        "task": task,
        "fork": fork,
        "review": dict(),
        "release": dict(),
        "masters": {},
        "tags": {},
        "inactive": False,
        "parents": {},
        "children": {},
        "comments": {},
        "comment": comment,
        "creator": utils.getUser(),
        "created": time.time(),
        "status": {"art": "ns", "tec": "ns"},
        "production": {"bid": 0, "delivery": 20140611.5, "spent": 0,
                       "assigned": ""},
        "subscribers": {}
    }

    # Add extra data if needed
    doc.update(overdoc)

    # Save data structure into the database
    _id, _rev = db.save(doc)
    if not debug:
        print "createTask: Added %r to project %r" % (asset, project)
    return db[_id]
Exemple #26
0
def user(username):
        user = utils.getUser(username)
        if user is not None:
                return render_template("user.html", user = user) 
        return error()
Exemple #27
0
        self._createUI()

    def _createUI(self):
        padx = 10
        pady = 5
        view = JahresdatenBaseView(self)
        view.grid(column=0, row=0, sticky='nswe', padx=padx, pady=pady)
        self._jahresdatenbaseview = view

    def setValues(self, jdcoll_list: List[JahresdatenCollection]) -> None:
        self._jahresdatenbaseview.setValues(jdcoll_list)


if __name__ == '__main__':
    from jahresdatenprovider import JahresdatenProvider
    import utils

    prov = JahresdatenProvider()
    prov.connect(utils.getUser())
    l: List[JahresdatenCollection] = prov.getJahresdatenAlleWohnungen(2020)

    root = Tk()
    root.rowconfigure(0, weight=1)
    root.columnconfigure(0, weight=1)

    dlg = WohnungVergleichDialog(root)
    #dlg.grid(column=0, row=0, sticky='nswe', padx=10, pady=10)
    dlg.setValues(l)

    root.mainloop()
    def _createConferenceObject(self, request):
        """Create a Conference object, returning ConferenceForm/request."""
        
        # Getting and Verifying current user
        user = getUser()

        # get the user_id (email) 
        user_id = getUserId(user)

        # Checking if the name field is filled out. 
        checkFieldValue(request.name)

        # copy ConferenceForm/ProtoRPC Message into dict
        data = ({field.name: getattr(request, field.name)
                for field in request.all_fields()})
        
        # Getting deleted because they are not part of the ndb model
        del data['websafeKey']
        
        del data['organizerDisplayName']
        
        # add default values for those missing
        for df in CONFERENCE_DEFAULTS:
            
            if data[df] in (None, []):
            
                data[df] = CONFERENCE_DEFAULTS[df]
            
                setattr(request, df, CONFERENCE_DEFAULTS[df])
        
        # convert dates TO strings using the Date objects
        if data['startDate']:
            
            data['startDate'] = datetime.strptime(
                                    data['startDate'][:10], "%Y-%m-%d").date()
            
            data['month'] = data['startDate'].month
        
        else:
            
            data['month'] = 0
        
        if data['endDate']:
        
            data['endDate'] = datetime.strptime(
                data['endDate'][:10], "%Y-%m-%d").date()

        # set seatsAvailable to be same as maxAttendees on creation
        if data["maxAttendees"] > 0:
        
            data["seatsAvailable"] = data["maxAttendees"]

        #---- Generate a Profile Key based on user ID and Conference ----
        
        # Profile key
        p_key = ndb.Key(Profile, user_id)

        # allocate new Conference ID with Profile key as parent
        c_id  = Conference.allocate_ids(size=1, parent=p_key)[0]

        # make Conference key using p_key and c_id 
        c_key = ndb.Key(Conference, c_id, parent=p_key)

        # Update stored conference with profile and conference key
        data['key'] = c_key
        
        data['organizerUserId'] = request.organizerUserId = user_id
        
        # create Conference, send email to organizer confirming
        # creation of Conference & return (modified) ConferenceForm
        Conference(**data).put()
        
        # cron job
        taskqueue.add(
            
            params = {
                'email'   : user.email(),
                'subject' : 'You Created a New Conference!',
                'body'    : 'Here are the details for your conference:',
                'info'    : repr(request)},
            
            url    = '/tasks/send_confirmation_email')    
        
        return request
Exemple #29
0
def createProject(name="", comment="Default", db_server="", sync_root="",
                  overdoc=dict(), site_root="/badass"):
    """
    This function create a project.

    :param name: The project name
    :type name: str
    :param comment: The project comment
    :type comment: str
    :param db_server: The data base adress
    :type db_server: str
    :param sync_root: The host data server root adress
    :type sync_root: str
    :param site_root: The site root folder
    :type site_root: str
    :param overdoc: A dictionnary that contains extra document attributes.
    :type overdoc: dict
    :returns:  couchdb.client.Database -- return the db.
    :raises: AttributeError, KeyError

    **Example:**

    >>> createProject(name="prod", comment="this is the project prod",
                    db_server="admin:[email protected]:5984",
                    sync_root="[email protected]:/homeworks" )
    """
    # Check if DB server exists
    adress = "http://%s/" % db_server
    exists = serverExists(adress)

    if site_root[0] is not "/":
        site_root = "/" + site_root

    if not exists:
        print "createProject(): Wrong DB server adress,user or/and password"
        return False

    # Check args
    if name == "":
        print "CreateProject(): Please provide a project name"
        return False

    if db_server == "" or db_server is None:
        print "CreateProject(): No server adress provided"
        return False

    # Check if DB and project already exist
    db = getDb(name, adress)

    # If DB and project exists return
    if db:
        print "CreateProject(): Project already exists."
        return False

    # Adding db project documents
    assets = utils.getAssetTypes()
    tasks = utils.getAssetTasks()

    # Users
    users = dict()
    user = utils.getUser()
    users[user] = "admin"

    doc = {
        "_id": "%s" % name,
        "type": "project",
        "name": name,
        "comment": comment,
        "asset_types": assets,
        "asset_tasks": tasks,
        "creator": user,
        "created": time.time(),
        "root": site_root,
        "users": users,
        "status": {"art": "ns", "tech": "ns"},
        "host": sync_root
    }

    doc.update(overdoc)
    # get views document
    views = getDefaultViews()
    if views and doc:
        # Create DB
        db = createDb(name, adress)
        _id, _rev = db.save(doc)
        _id, _rev = db.save(views)
        print "createProject(): Project '%s' created" % (name)
    else:
        print "createProject(): Can't create Project '%s'" % (name)
    return db