• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python models.Message类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中models.Message的典型用法代码示例。如果您正苦于以下问题:Python Message类的具体用法?Python Message怎么用?Python Message使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Message类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get

    def get(self):
        
        # Get the id that indicate where is the start point of new messages:
        current_id = int(self.request.get('id'))
        messages = Message.all().order('-postID').filter("postID > ", current_id)
        msg_set  = messages.fetch(10)
 
        self.response.headers['Content-Type'] = 'text/xml'
        self.response.headers['Cache-Control'] = 'no-cache'
        
        # Start writing the xml content:
        self.response.out.write('<?xml version="1.0"?>\n')
        self.response.out.write('    <response>\n')
        self.response.out.write('        <id>%d</id>\n' % Message.max_id() )
        for msg in msg_set:
            if not msg.isRemoved:
                self.response.out.write('        <message>\n')
                self.response.out.write('            <author>%s</author>\n' % msg.author.nickname() )
                self.response.out.write('            <postID>%d</postID>\n' % msg.postID )
                self.response.out.write('            <content>%s</content>\n' % msg.content )
                self.response.out.write('            <rcount>%d</rcount>\n' % msg.rCount )
                self.response.out.write('            <time>%s</time>\n' % msg.postDate )
                self.response.out.write('        </message>\n')            

        self.response.out.write('    </response>\n')
开发者ID:benjamin99,项目名称:3dAR,代码行数:25,代码来源:main.py


示例2: put

 def put():
     key = ndb.Key('Message', pk)
     msg = key.get()
     if msg:
         msg = Message(key=key, **form.data)
         msg.put()
     return msg
开发者ID:tarvitz,项目名称:test-work,代码行数:7,代码来源:views.py


示例3: restore_object

    def restore_object(self, attrs, instance=None):
        user = self.context['request'].user
        classgroup = attrs.get('classgroup')

        attributes = ["text", "source", "reply_to"]

        if (classgroup.class_settings is not None and
            classgroup.class_settings.enable_posting is False and
            not ClassGroupPermissions.is_teacher(classgroup, user)):
            raise serializers.ValidationError("You are not allowed to make a post right now.")


        if instance is None:
            instance = Message(user=user, classgroup=classgroup)
        else:
            if instance.user != user:
                raise serializers.ValidationError("Attempting to edit a message that is not yours.")

        message_type = attrs.get('message_type')
        if message_type == "A" and not ClassGroupPermissions.is_teacher(classgroup, user):
            raise serializers.ValidationError("You cannot make an announcement unless you own a course.")

        instance.message_type = message_type

        instance = set_attributes(attributes, attrs, instance)
        instance.save()
        return instance
开发者ID:VikParuchuri,项目名称:movide,代码行数:27,代码来源:serializers.py


示例4: send_msg

def send_msg(request):
    response = {}
    info = ""
    try:
        if request.method == 'POST':
            req = request.POST
            recv_user = req.get('recv_user')
            send_user = req.get('send_user')
            title = req.get('title')
            content = req.get('content')
            msg = Message(title=title, content=content)
            # 发送者ID为1则是系统信息
            if send_user == 1:
                msg.category = 1
            msg.save()
            user_msg = UserMessage(recv_user=recv_user,send_user=send_user,message=msg)
            user_msg.save()
            response['status'] = user_msg.status

    except:
        info = "%s || %s" % (sys.exc_info()[0], sys.exc_info()[1])
        return HttpResponse(info)

    response_json = simplejson.dumps(response)
    return HttpResponse(response_json)
开发者ID:yinzhedfs,项目名称:django_demo,代码行数:25,代码来源:views.py


示例5: _enqueue_lead_message

def _enqueue_lead_message(lead):
	params = {
		'message_type': 'OFFER_TO_PROPERTY_OWNER',
		'params': json.dumps(lead)
	}

	Message.enqueue(params)
开发者ID:armandomiani,项目名称:flask-appengine-bootstrap,代码行数:7,代码来源:leads.py


示例6: do_ntranslate

def do_ntranslate(singular, plural, number, translation_function):
    language = trans_real.get_language()

    translation = trans_real.translation(language)
    number = translation.plural(number)

    kw = {'msgid': singular, 'plural': number, 'language': language,
            'domain': 'django'}
    try:
        message = Message.objects.get(**kw)
    except Message.DoesNotExist:
        # Miss
        msgstr = do_ntranslate_old(singular, plural, number,
                                   translation_function)
        kw['msgstr'] = msgstr
        message = Message(**kw)
        message.save()
        return msgstr

    # Hit
    translation = message.translation
    if not translation:
        return do_ntranslate_old(singular, plural, number,
                                 translation_function)

    return translation
开发者ID:emencia,项目名称:django-localizer,代码行数:26,代码来源:__init__.py


示例7: message_send

def message_send(service):
    text = request.form.get('message')
    if not text:
        return Error.ARGUMENT_MISSING('message')

    subscribers = Subscription.query.filter_by(service=service).count()
    if subscribers == 0:
        # Pretend we did something even though we didn't
        # Nobody is listening so it doesn't really matter
        return Error.NONE

    level = (request.form.get('level') or '3')[0]
    level = int(level) if level in "12345" else 3
    title = request.form.get('title', '').strip()[:255]
    link = request.form.get('link', '').strip()
    msg = Message(service, text, title, level, link)
    db.session.add(msg)
    db.session.commit()

    if google_api_key or current_app.config['TESTING']:
        Gcm.send_message(msg)

    if zeromq_relay_uri:
        queue_zmq_message(json_encode({"message": msg.as_dict()}))

    service.cleanup()
    db.session.commit()
    return Error.NONE
开发者ID:Pushjet,项目名称:Pushjet-Server-Api,代码行数:28,代码来源:message.py


示例8: handle_received_message

    def handle_received_message(self,
        sender, room_id, username, message, date, **kwargs):
        """
        Default handler for the message_received signal.
        1 - Saves an instance of message to db
        2 - Appends a tuple (message_id, message_obj)
            to the sender.messages queue
        3 - Signals the "New message" event on the sender (decorator)
        4 - Returns the created message

        """
        room = Room.objects.get(id=room_id)
        fields = {
            'room': room,
            'date': date,
            'content': message,
            'username': username,
        }
        user = kwargs.get('user')
        if user:
            fields['user'] = user
        # 1
        new_message = Message(**fields)
        new_message.save()

        # 2
        msg_number = sender.get_next_message_id(room_id)
        messages_queue = sender.get_messages_queue(room_id)
        messages_queue.append((msg_number, new_message))

        # 3 - decorator does
        # sender.signal_new_message_event(room_id)

        # 4
        return new_message
开发者ID:Mondego,项目名称:pyreco,代码行数:35,代码来源:allPythonContent.py


示例9: create_message

def create_message(email_message):
    if email_message:
        message = Message()
        message.subject = email_message.subject
        message.sent_date = email_message.sent_date
        message.message_id = email_message.message_id
        message.thread_id = email_message.thread_id  # where should this logic live?
开发者ID:thechild,项目名称:mbox2sql,代码行数:7,代码来源:importing.py


示例10: obj_get_list

 def obj_get_list(self, bundle, **kwargs):
     user = bundle.request.GET.get('user_id') #extracts user_id from URL params
     if bundle.request.GET.get('received'):
         received = False if bundle.request.GET.get('received') == "false" else True
         return Message.objects(user_id=user, received=received)
     else:
         return Message.objects(user_id=user)
开发者ID:danboey,项目名称:LocationBasedMessaging,代码行数:7,代码来源:api.py


示例11: post

 def post(self):
     "We receive post data from IMified"
     userkey = self.request.get('userkey')
     network = self.request.get('network')
     # remove any markup from messages
     msg = HTML_ELEMENTS.sub('', self.request.get('msg'))
     step = self.request.get('step')
     try:
         # we try and create the message
         message = Message(
             userkey = userkey,
             network = network,
             msg = msg,
             step = int(step)
         )   
         message.put()
         # send an email with the message on
         mail.send_mail(sender="[email protected]",
                       to="Gareth Rushgrove <[email protected]>",
                       subject="New message posted on IMified demo",
                       body=msg)
         # we just added a message so we need to clear our cache
         memcache.delete("index")
         # simple logging
         logging.info("Saved new message")
         # the response is send as an IM message to the sender
         self.response.out.write('Message saved')
     except:
         # we'll log the error if it occurs
         # and report we couldn't save the message to the sender
         logging.error("Error occured creating new message")
         self.response.out.write('An error ocured, message not saved')
开发者ID:frankk00,项目名称:appengine-imified,代码行数:32,代码来源:main.py


示例12: post

 def post(self):
     request_dict = request.get_json()
     if not request_dict:
         response = {'message': 'No input data provided'}
         return response, status.HTTP_400_BAD_REQUEST
     errors = message_schema.validate(request_dict)
     if errors:
         return errors, status.HTTP_400_BAD_REQUEST
     message_message = request_dict['message']
     if not Message.is_unique(id=0, message=message_message):
         response = {'error': 'A message with the same message already exists'}
         return response, status.HTTP_400_BAD_REQUEST
     try:
         category_name = request_dict['category']['name']
         category = Category.query.filter_by(name=category_name).first()
         if category is None:
             # Create a new Category
             category = Category(name=category_name)
             db.session.add(category)
         # Now that we are sure we have a category
         # create a new Message
         message = Message(
             message=message_message,
             duration=request_dict['duration'],
             category=category)
         message.add(message)
         query = Message.query.get(message.id)
         result = message_schema.dump(query).data
         return result, status.HTTP_201_CREATED
     except SQLAlchemyError as e:
         db.session.rollback()
         resp = {"error": str(e)}
         return resp, status.HTTP_400_BAD_REQUEST
开发者ID:xianjunzhengbackup,项目名称:code,代码行数:33,代码来源:views.py


示例13: get

 def get(self):
     chat_key = self.request.get('key')
     form = self.request.get('format')
     
     if form == 'json':
         self.response.out.headers['Content-Type'] = 'application/zip'
         in_memory = StringIO()
         zmemory = zipfile.ZipFile(in_memory,
                                   "w",
                                   zipfile.ZIP_DEFLATED)
         zmemory.writestr(
             'messages.json',
             '[ {} ]'.format(','.join(
                 [json.dumps(m) for m in Message.query_all_from_chat(chat_key,limit=False)])))
         in_memory.seek(0)
         zmemory.close()
         
         self.response.out.write(in_memory.read())
         
     else:
         self.response.out.headers['Content-Type'] = 'text/plain'
         for message in Message.query_all_from_chat(chat_key,limit=True):
             self.response.out.write(
                 u'{}, {}: {}\n'.format(message['author'],
                                        message['date'],
                                        message['text'])
             )
开发者ID:guillemborrell,项目名称:cloudchat,代码行数:27,代码来源:rest.py


示例14: send

def send(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)

        if form.is_valid():
            msg = Message()
            msg.username = form.cleaned_data['username']
            msg.email = form.cleaned_data['email']
            msg.phone = form.cleaned_data['phone']
            msg.location = form.cleaned_data['location']
            msg.job = form.cleaned_data['job']
            msg.description = form.cleaned_data['description']
            msg.area = form.cleaned_data['area']

            try:
                msg.save()
                mail_managers('ZUBIRD webpage - new message received', 'Otrzymałeś nową wiadomość.')
            except Exception as e:
                import traceback
                logger.error(str(e))
                logger.error(traceback.format_exc())
                return render_to_response('error.html', {})
            
            return render_to_response('thanks.html', {})
        else:
            return render_to_response('base.html', Context({'form':form}))
    else:
        return index(request)    
开发者ID:kjopek,项目名称:zubird_webapp,代码行数:28,代码来源:views.py


示例15: post

    def post(self, *args, **kwargs):
        groupname = kwargs['groupname']
        query = Group.query(Group.name == groupname)
        groups = query.fetch()
        if len(groups) == 1:
            thisGroup = groups[0]
        else:
            thisGroup = None


        user = self.user

        print(user)
        if user:
            memberships = GroupMembership.query(GroupMembership.userKey == user.key,
                                                GroupMembership.groupKey == thisGroup.key).fetch()
            if len(memberships) == 1:
                membership = memberships[0]
                print(membership)
            else:
                self.display_message('You can only post if you\'re a member')

                return

        if user:
            print(self.request.get('message'))
            newMessage = Message(parent=thisGroup.key, userKey=user.key, text=self.request.get('message'))
            newMessage.put()

        self.redirect('/{groupname}/show'.format(groupname = groupname))
开发者ID:fi4sk0,项目名称:supertinygroupware,代码行数:30,代码来源:main.py


示例16: add_message_without_storage

def add_message_without_storage(to_user, from_user, level, message, extra_tags='', fail_silently=False, subject='', mail=False, expires=None, close_timeout=None):
    """
    Use this method to add message without having to pass a `request.storage`
    """
    from models import Message
    message = Message(user=to_user, level=level, message=message, extra_tags=extra_tags, subject=subject, from_user=from_user, expires=expires, close_timeout=close_timeout)
    return message.save()
开发者ID:maraujop,项目名称:django-persistent-messages,代码行数:7,代码来源:api.py


示例17: _enqueue_job_message

def _enqueue_job_message(job, message_type):
	params = {
		'message_type': message_type,
		'params': json.dumps(job.to_json())
	}

	Message.enqueue(params)
开发者ID:armandomiani,项目名称:flask-appengine-bootstrap,代码行数:7,代码来源:notifications.py


示例18: save_msg

def save_msg():
    form = request.form
    author = form.get("author")
    content = form.get("content")
    msg = Message(author=author, content=content, time=datetime.now())
    msg.save()
    return jsonify(status='success')
开发者ID:03013314,项目名称:python-1,代码行数:7,代码来源:views.py


示例19: displaycontrol

def displaycontrol(request):
    """
    If the request is a GET, renders the display control dialog content. If it's
    a POST, uses the POST data to send a Message to Harvest. That Message
    requests a change to a given client's display's hardware state, depending on
    the command specified in the request.
    The client's user must be an administrator for the Message to be sent.
    """
    if request.method == 'GET':
        return render_to_response('orwell/displaycontrol.html',
                                  {},
                                  context_instance=RequestContext(request))
    else:
        if not request.user.is_staff:
            return HttpResponse('DISALLOWED')
        clientid = request.POST.get('client', '')
        client = get_object_or_404(Client, client_id=clientid)
        setpower = request.POST.get('setpower', '')
        cmd = request.POST.get('cmd', '')
        arg = request.POST.get('arg', '')
        packet = {'to':client.jid(), 'method':'displaycontrol'}
        if setpower == 'kill':
            packet['method'] = 'killDDS'
        if setpower in ['on', 'off']:
            packet['setpower'] = setpower == 'on'
        elif cmd != '' and arg != '':
            packet['cmd'] = {'cmd':cmd, 'arg':arg}
        if (('setpower' in packet) or ('cmd' in packet)
            or (packet['method'] == 'killDDS')):
            m = Message(message=json.dumps(packet))
            m.save()
        return HttpResponse('OK')
开发者ID:crew,项目名称:dds-backend,代码行数:32,代码来源:views.py


示例20: postmessage

def postmessage(request):
    name = request.POST['name']
    text = request.POST['text']

    m = Message(name=name, text=text)
    m.save()

    return HttpResponseRedirect(reverse('board'))
开发者ID:03013314,项目名称:python-1,代码行数:8,代码来源:views.py



注:本文中的models.Message类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.Move类代码示例发布时间:2022-05-27
下一篇:
Python models.Member类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap