python Python - 有用的片段
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Python - 有用的片段相关的知识,希望对你有一定的参考价值。
from __future__ import unicode_literals
from twilio.rest import Client
from django.core.exceptions import MiddlewareNotUsed
import os
import logging
import json
logger = logging.getLogger(__name__)
MESSAGE = """ALERT! It appears the server is having issues.
Exception: %s. Go to: http://newrelic.com for more details."""
NOT_CONFIGURED_MESSAGE = """Cannot initialize Twilio notification
middleware. Required enviroment variables TWILIO_ACCOUNT_SID, or
TWILIO_AUTH_TOKEN or TWILIO_NUMBER missing"""
def load_admins_file():
with open('config/administrators.json') as adminsFile:
admins = json.load(adminsFile)
return admins
def load_twilio_config():
twilio_account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
twilio_auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
twilio_number = os.environ.get('TWILIO_NUMBER')
if not all([twilio_account_sid, twilio_auth_token, twilio_number]):
logger.error(NOT_CONFIGURED_MESSAGE)
raise MiddlewareNotUsed
return (twilio_number, twilio_account_sid, twilio_auth_token)
class MessageClient(object):
def __init__(self):
(twilio_number, twilio_account_sid,
twilio_auth_token) = load_twilio_config()
self.twilio_number = twilio_number
self.twilio_client = Client(twilio_account_sid,
twilio_auth_token)
def send_message(self, body, to):
self.twilio_client.messages.create(body=body, to=to,
from_=self.twilio_number,
)
# imageUrl = string
def send_message_img(self, body, to, imageUrl):
self.twilio_client.messages.create(body=body, to=to,
from_=self.twilio_number,
media_url=[imageUrl])
)
class TwilioNotificationsMiddleware(object):
def __init__(self):
self.administrators = load_admins_file()
self.client = MessageClient()
def process_exception(self, request, exception):
exception_message = str(exception)
message_to_send = MESSAGE % exception_message
for admin in self.administrators:
self.client.send_message(message_to_send, admin['phone_number'])
logger.info('Administrators notified')
return None
###############################
### TWilio simple 12 line message script
### See https://www.twilio.com for more details
###############################
import os
from twilio.rest import Client
account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
client = Client(account_sid, auth_token)
client.messages.create(from_=os.environ.get('TWILIO_PHONE_NUMBER'),
to=os.environ.get('CELL_PHONE_NUMBER'),
body='You just sent an SMS from Python using Twilio!')
以上是关于python Python - 有用的片段的主要内容,如果未能解决你的问题,请参考以下文章