本文整理汇总了Python中models.Message类的典型用法代码示例。如果您正苦于以下问题:Python Message类的具体用法?Python Message怎么用?Python Message使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Message类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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')
示例2: put
def put():
key = ndb.Key('Message', pk)
msg = key.get()
if msg:
msg = Message(key=key, **form.data)
msg.put()
return msg
示例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
示例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)
示例5: _enqueue_lead_message
def _enqueue_lead_message(lead):
params = {
'message_type': 'OFFER_TO_PROPERTY_OWNER',
'params': json.dumps(lead)
}
Message.enqueue(params)
示例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
示例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
示例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
示例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?
示例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)
示例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')
示例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
示例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'])
)
示例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)
示例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))