code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Core.Packets { public abstract class Packet { protected byte numeroConnexion; protected byte typePacket; public byte NumeroConnexion { get { return numeroConnexion; } } public byte TypePacket { get { return typePacket; } } public PacketTypes Primitive { get { return (PacketTypes)Enum.Parse(typeof(PacketTypes), typePacket.ToString()); } } //public static Packet CreatePacketFromCharOfBitArray(string arrayOfBits) //{ // Packet packet; // byte numeroConnexion; // byte typeConnexion; // for (int ctr = 0; ctr < 16; ctr += 8) // { // numeroConnexion = Convert.ToByte(arrayOfBits.Substring(ctr, 8), 2); // } // switch( // return packet; //} public virtual string GetStringOfBitArray() { string arrayOfBits; arrayOfBits = Convert.ToString(numeroConnexion, 2).PadLeft(8, '0'); arrayOfBits += Convert.ToString(typePacket, 2).PadLeft(8, '0'); return arrayOfBits; } public static PacketTypes GetPacketType(byte type) { return (PacketTypes)Enum.Parse(typeof(PacketTypes), type.ToString()); } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Main/Packets/Paquet.cs
C#
asf20
1,499
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Main.PrimitivesCommunication; namespace Main.Packets { public abstract class Packet { protected byte numeroConnexion; protected PacketType packetType; protected Packet() { } protected Packet(byte numeroConnexion, PacketType type) { this.numeroConnexion = numeroConnexion; this.packetType = type; } #region Properties [JsonProperty(Order = 1)] public byte NumeroConnexion { get { return numeroConnexion; } set { numeroConnexion = value; } } [JsonProperty(Order = 2)] public PacketType PacketType { get { return packetType; } set { packetType = value; } } #endregion public abstract void WriteJson(StreamWriter sw); public static Packet ReadJson(StreamReader sr) { Packet p = null; PacketType packetType; string str = sr.ReadLine(); string stringType = string.Empty; JObject objPacket = (JObject)JsonConvert.DeserializeObject(str); JProperty propsOfPacket = objPacket.Property("PacketType"); JObject objPacketType = (JObject)JsonConvert.DeserializeObject(propsOfPacket.Value.ToString()); foreach (JToken token in objPacketType.PropertyValues()) { stringType += token.ToString(); } packetType = PacketType.CreateTypeForPacket(stringType); switch (packetType.Type) { case PacketTypes.ConnectionRequestPacket: case PacketTypes.ConnectionConfirmationPacket: p = ConnectionPacket.CreateConnectionPacket(str); break; case PacketTypes.DataPacket: p = DataPacket.CreateDataPacket(str); break; case PacketTypes.NegativeAcknowledgmentPacket: case PacketTypes.PositiveAcknowledgmentPacket: p = AcknowledgementPacket.CreateAcknowledgementPacket(str); break; case PacketTypes.FreeConnectionPacket: p = FreeConnectionPacket.CreateFreeConnectionPacket(str); break; default: throw new NotImplementedException(); } return p; } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Main/Packets/Packet.cs
C#
asf20
2,722
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Core.Packets { public enum DisconnectRaison { DeclinedByDestination = 1, DeclinedByProvider } public class DisconnectionPacket : Packet { private byte adresseSource; private byte adresseDestination; private byte raison; private DisconnectionPacket(byte numeroConnexion, byte typePacket, byte adresseSource, byte adresseDestination, byte raison) { this.numeroConnexion = numeroConnexion; this.typePacket = typePacket; this.adresseSource = adresseSource; this.adresseDestination = adresseDestination; this.raison = raison; } public byte AdresseSource { get { return adresseSource; } } public byte AdresseDestination { get { return adresseDestination; } } public static DisconnectionPacket CreateFreeConnectionPacket(int numeroConnexion, int adresseSource, int adresseDestination, DisconnectRaison raison) { DisconnectionPacket requestPacket = new DisconnectionPacket(Convert.ToByte(numeroConnexion), (byte)PacketTypes.FreeConnectionPacket, Convert.ToByte(adresseSource), Convert.ToByte(adresseDestination), (byte)raison); return requestPacket; } public void CreatePacketFromCharOfBitArray() { } public override string GetStringOfBitArray() { //numeroConnexion = 3; //adresseSource = 34; //adresseDestination = 56; //raison = (byte)DisconnectRaison.DeclinedByDestination; string arrayOfBits = base.GetStringOfBitArray(); arrayOfBits += Convert.ToString(adresseSource, 2).PadLeft(8, '0'); arrayOfBits += Convert.ToString(adresseDestination, 2).PadLeft(8, '0'); arrayOfBits += Convert.ToString(raison, 2).PadLeft(8, '0'); return arrayOfBits; } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Main/Packets/DisconnectionPaquet.cs
C#
asf20
2,369
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Core.Paquets { public class Packet3 { private Packet3 pdu; } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Main/Packets/Packet3.cs
C#
asf20
195
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Core.Packets { public class ConnectionPacket : Packet { private byte adresseSource; private byte adresseDestination; private ConnectionPacket(byte numeroConnexion, byte typePacket, byte adresseSource, byte adresseDestination) { this.numeroConnexion = numeroConnexion; this.typePacket = typePacket; this.adresseSource = adresseSource; this.adresseDestination = adresseDestination; } public byte AdresseSource { get { return adresseSource; } } public byte AdresseDestination { get { return adresseDestination; } } public static ConnectionPacket CreateRequestConnectionPacket(int numeroConnexion, int adresseSource, int adresseDestination) { ConnectionPacket requestPacket = new ConnectionPacket(Convert.ToByte(numeroConnexion), (byte)PacketTypes.RequestConnectionPacket, Convert.ToByte(adresseSource), Convert.ToByte(adresseDestination)); return requestPacket; } public static ConnectionPacket CreateConfirmationConnectionPacket(int numeroConnexion, int adresseSource, int adresseDestination) { ConnectionPacket requestPacket = new ConnectionPacket(Convert.ToByte(numeroConnexion), (byte)PacketTypes.ConfirmationConnectionPacket, Convert.ToByte(adresseSource), Convert.ToByte(adresseDestination)); return requestPacket; } public override string GetStringOfBitArray() { string arrayOfBits = base.GetStringOfBitArray(); arrayOfBits += Convert.ToString(adresseSource, 2).PadLeft(8, '0'); arrayOfBits += Convert.ToString(adresseDestination, 2).PadLeft(8, '0'); return arrayOfBits; } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Main/Packets/ConnectionPaquet.cs
C#
asf20
2,293
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Main.Packets { public class ConnectionPacket : Packet { private byte adresseSource; private byte adresseDestination; public ConnectionPacket() { } private ConnectionPacket(byte numeroConnexion, PacketType type, byte source, byte destination) : base(numeroConnexion, type) { this.adresseSource = source; this.adresseDestination = destination; } [JsonProperty(Order = 10)] public byte AdresseSource { get { return adresseSource; } set { adresseSource = value; } } [JsonProperty(Order = 20)] public byte AdresseDestination { get { return adresseDestination; } set { adresseDestination = value; } } public static ConnectionPacket CreateRequestConnectionPacket(byte numeroConnexion, byte source, byte destination) { ConnectionPacket packet = new ConnectionPacket(numeroConnexion, PacketType.CreateTypeForConnectionRequestPacket(), source, destination); return packet; } public static ConnectionPacket CreateConnectionConfirmationPacket(byte numeroConnexion, byte source, byte destination) { ConnectionPacket packet = new ConnectionPacket(numeroConnexion, PacketType.CreateTypeForConnectionConfirmationPacket(), source, destination); return packet; } public static ConnectionPacket CreateConnectionPacket(string str) { return JsonConvert.DeserializeObject<ConnectionPacket>(str) as ConnectionPacket; } public override void WriteJson(System.IO.StreamWriter sw) { sw.WriteLine(JsonConvert.SerializeObject(this)); } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Main/Packets/ConnectionPacket.cs
C#
asf20
1,979
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace Core.Packets { public class DataPacket : Packet { private const int DATA_SIZE = 128; private byte[] data = new byte[DATA_SIZE]; private DataPacket(byte numeroConnexion, byte typePacket, byte[] data) { this.numeroConnexion = numeroConnexion; this.typePacket = typePacket; this.data = data; } public byte[] Data { get { return data; } set { data = value; } } public static Packet[] CreateDataPackets(PDUSession PduSession, int prActuel, int psActuel) { //TODO s'assurer que les data remplisse les 128 bytes de données pour que le packet soit toujours de la même longueur int ctr = 0; byte[] array = Encoding.ASCII.GetBytes(PduSession.Data); Packet[] paquets = new Packet[(int)Math.Ceiling((double)array.Length / (double)128)]; while(ctr < paquets.Length) { //paquets[ctr] = new DataPacket(Convert.ToByte(PduSession.ApplicationId), CreatePacketType(prActuel, true, psActuel), array); } return paquets; } //private static byte CreatePacketType(int pr, bool lastPacket, int ps) //{ // BitArray originalBitArray = new BitArray(8); // string binary = Convert.ToString(pr, 2).PadLeft(3, '0'); // for (int ctr = 0; ctr < binary.Length; ctr++) // { // originalBitArray[ctr] = binary[ctr].ToString().Equals("1"); // } // originalBitArray[3] = !lastPacket; // binary = Convert.ToString(ps, 2).PadLeft(3, '0'); // for (int ctr = 4; ctr < binary.Length + 4; ctr++) // { // originalBitArray[ctr] = binary[ctr - 4].ToString().Equals("1"); // } // originalBitArray[7] = false; // return ConvertBitArrayToByte(originalBitArray); //} public void CreatePacketFromCharOfBitArray() { } public override string GetStringOfBitArray() { string arrayOfBits = string.Empty; foreach(byte dataByte in data) { arrayOfBits += Convert.ToString(dataByte, 2).PadLeft(8, '0'); } return arrayOfBits; } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Main/Packets/DataPaquet.cs
C#
asf20
2,529
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Main.Packets { public class DataPacket : Packet { private const int MAX_BYTES = 128; private string data; private DataPacket(byte numeroConnexion, PacketType type, string data) : base(numeroConnexion, type) { this.data = data; } [JsonProperty(Order = 15)] public string Data { get { return data; } set { data = value; } } public static List<DataPacket> CreateDataPackets(byte numeroConnexion, int pr, int ps, string data) { int length; bool hasNext; DataPacket packet; List<DataPacket> packets = new List<DataPacket>(); for (int i = 0; i < data.Length; i += MAX_BYTES) { hasNext = ((i + MAX_BYTES) < data.Length); length = Math.Min(data.Length - i, MAX_BYTES); packet = new DataPacket(numeroConnexion, PacketType.CreateTypeForDataPacket(pr, hasNext, ps), data.Substring(i, length)); packets.Add(packet); } return packets; } public static DataPacket CreateDataPacket(string str) { return JsonConvert.DeserializeObject<DataPacket>(str) as DataPacket; } public override void WriteJson(System.IO.StreamWriter sw) { sw.WriteLine(JsonConvert.SerializeObject(this)); } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Main/Packets/DataPacket.cs
C#
asf20
1,634
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Core.Paquets { public enum PaquetTypes { RequestConnectionPaquet = 11, ConfirmationConnectionPaquet = 15, FreeConnectionPaquet = 19 } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Main/Packets/EnumTypePaquet.cs
C#
asf20
286
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Main.Packets { public class AcknowledgementPacket : Packet { public AcknowledgementPacket(byte numeroConnexion, PacketType type) : base(numeroConnexion, type) { } public static AcknowledgementPacket CreateAcknowledgementPacket(string str) { return JsonConvert.DeserializeObject<AcknowledgementPacket>(str) as AcknowledgementPacket; } public override void WriteJson(System.IO.StreamWriter sw) { sw.WriteLine(JsonConvert.SerializeObject(this)); } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Main/Packets/AcknowledgementPacket.cs
C#
asf20
722
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using Main.Transport; using Main.Reseau; using System.Threading; namespace Main { class Program { static void Main(string[] args) { Console.SetWindowSize(200, 40); CoucheTransport coucheTransport = new CoucheTransport(); Thread threadTransportVersReseau = new Thread(coucheTransport.EcrireVersReseau); Thread threadLireDeReseau = new Thread(coucheTransport.LireDeReseau); CoucheReseau coucheReseau = new CoucheReseau(); Thread threadLireDeTransport = new Thread(coucheReseau.LireDeTransport); Thread threadEcrireVersTransport = new Thread(coucheReseau.EcrireVersTransport); // Demarrage des threads threadTransportVersReseau.Start(); threadLireDeTransport.Start(); threadEcrireVersTransport.Start(); threadLireDeReseau.Start(); threadTransportVersReseau.Join(); //threadReseau.Join(); //threadTransportVersReseau.Join(); } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Main/Program.cs
C#
asf20
1,206
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Timers; namespace Main.Reseau { public enum EtatsConnexion { ConnexionEtablie, EnAttente } public class Connexion { private static List<Connexion> listeConnexions = new List<Connexion>(); private byte idConnexionLogique; private EtatsConnexion etat; private byte adresseSource; private byte adresseDestination; private int pr; private int ps; private Timer timer; private Connexion(byte adresseSource, byte adresseDestination) { if (listeConnexions.Count > 0) this.idConnexionLogique = (byte)(listeConnexions.Max(c => c.idConnexionLogique) + 1); else this.idConnexionLogique = 1; this.etat = EtatsConnexion.EnAttente; this.adresseSource = adresseSource; this.adresseDestination = adresseDestination; this.pr = 0; this.ps = 0; } public byte IdConnexionLogique { get { return idConnexionLogique; } } public EtatsConnexion Etat { get { return etat; } set { etat = value; } } public byte AdresseSource { get { return adresseSource; } } public byte AdresseDestination { get { return adresseDestination; } } public static List<Connexion> ListeConnexions { get { return listeConnexions.ToList(); } } public static Connexion CreateConnexion(byte adresseSource, byte adresseDestination) { Connexion connexion = new Connexion(adresseSource, adresseDestination); listeConnexions.Add(connexion); return connexion; } public static void DeleteConnexion(Connexion connexion) { listeConnexions.Remove(connexion); } public int GetPS() { if (ps < 8) ps++; else ps = 0; return ps; } public int GetPR() { if (pr < 8) pr++; else pr = 0; return pr; } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Main/Reseau/ConnexionReseau.cs
C#
asf20
2,290
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.Pipes; using Main.PrimitivesCommunication; using System.IO; using System.Threading; using Main.Packets; using Newtonsoft.Json; namespace Main.Reseau { class CoucheReseau { private const int MULTIPLE_POUR_REFUS_CONNEXION_FOURNISSEUR = 27; private const int MULTIPLE_POUR_REFUS_CONNEXION_DISTANT = 13; private const int MULTIPLE_POUR_ABSENCE_REPONSE_CONNEXION = 19; private const int MULTIPLE_POUR_ABSENCE_ACQUITTEMENT = 15; NamedPipeClientStream reseauToTransportPipe; StreamWriter swReseauToTransport; public void LireDeTransport() { reseauToTransportPipe = new NamedPipeClientStream(REGLES.PIPE_RESEAU_TO_TRANSPORT); swReseauToTransport = new StreamWriter(reseauToTransportPipe); reseauToTransportPipe.Connect(); swReseauToTransport.AutoFlush = true; NamedPipeClientStream transportToReseauPipe = new NamedPipeClientStream(REGLES.PIPE_TRANSPORT_TO_RESEAU); NamedPipeServerStream reseauToReseauPipe = new NamedPipeServerStream(REGLES.PIPE_RESEAU_TO_RESEAU, PipeDirection.InOut, 10, PipeTransmissionMode.Message); Console.WriteLine(((PipeStream)transportToReseauPipe).IsAsync.ToString()); StreamReader sr = new StreamReader(transportToReseauPipe); StreamWriter swrr = new StreamWriter(reseauToReseauPipe); reseauToReseauPipe.WaitForConnection(); transportToReseauPipe.Connect(); transportToReseauPipe.ReadMode = PipeTransmissionMode.Message; Packet packetToSend = null; Primitive primitiveReponse; Connexion connexion; while (true) { Primitive pr = Primitive.ReadJson(sr); primitiveReponse = null; switch (pr.Primitives) { case Primitives.NConnectRequest: if (ConnexionAcceptee(pr.AdresseSource)) { connexion = Connexion.CreateConnexion(pr.AdresseSource, pr.AdresseDestination); packetToSend = ConnectionPacket.CreateRequestConnectionPacket(connexion.IdConnexionLogique, connexion.AdresseSource, connexion.AdresseDestination); EnvoieReseauVersLiaison(packetToSend); Packet packetReponse = EnvoieLiaisonVersReseau(packetToSend); if (packetReponse != null) { switch (packetReponse.PacketType.Type) { case PacketTypes.ConnectionConfirmationPacket: primitiveReponse = Primitive.CreateNConnectConf(((ConnectionPacket)packetReponse).AdresseDestination); break; case PacketTypes.FreeConnectionPacket: primitiveReponse = Primitive.CreateNDisconnectInd(((FreeConnectionPacket)packetReponse).AdresseDestination, ((FreeConnectionPacket)packetReponse).Raison); break; } } } else { primitiveReponse = Primitive.CreateNDisconnectInd(pr.AdresseSource, Raisons.FournisseurRefuse); } break; case Primitives.NDataRequest: break; case Primitives.NDisconnectRequest: break; } if (packetToSend != null) packetToSend.WriteJson(swrr); //EnvoieReseauVersLiaison(packetToSend); } //transportToReseauPipe.Close(); } public void EcrireVersTransport() { NamedPipeClientStream reseauToReseauPipe = new NamedPipeClientStream(REGLES.PIPE_RESEAU_TO_RESEAU); NamedPipeServerStream reseauToTransportPipe = new NamedPipeServerStream(REGLES.PIPE_RESEAU_TO_TRANSPORT,PipeDirection.InOut,10,PipeTransmissionMode.Message); StreamReader srrr = new StreamReader(reseauToReseauPipe); StreamWriter swrt = new StreamWriter(reseauToTransportPipe); reseauToReseauPipe.Connect(); reseauToTransportPipe.WaitForConnection(); reseauToReseauPipe.ReadMode = PipeTransmissionMode.Message; reseauToTransportPipe.ReadMode = PipeTransmissionMode.Message; Packet packet = Packet.ReadJson(srrr); Primitive primitiveReponse = null; switch (packet.PacketType.Type) { case PacketTypes.ConnectionConfirmationPacket: primitiveReponse = Primitive.CreateNConnectConf(((ConnectionPacket)packet).AdresseDestination); break; case PacketTypes.FreeConnectionPacket: primitiveReponse = Primitive.CreateNDisconnectInd(((FreeConnectionPacket)packet).AdresseDestination, ((FreeConnectionPacket)packet).Raison); break; default: throw new NotImplementedException(); } primitiveReponse.WriteJson(swrt); } private void EnvoieReseauVersLiaison(Packet p) { //Simulation de ce que Réseau réussi à envoyer à la couche liaison using (StreamWriter sw = new StreamWriter(REGLES.L_ECRITURE, true)) { p.WriteJson(sw); } } private void EnvoieSystemeBVersLiaison(Packet p) { using (StreamWriter sw = new StreamWriter(REGLES.L_LECTURE, true)) { p.WriteJson(sw); } } private Packet EnvoieLiaisonVersReseau(Packet packetRecu) { Packet packetEnvoye = null; switch (packetRecu.PacketType.Type) { case PacketTypes.ConnectionRequestPacket: ConnectionPacket connectionPacket = (ConnectionPacket)packetRecu; if ((connectionPacket.AdresseSource % MULTIPLE_POUR_REFUS_CONNEXION_DISTANT) == 0) { FreeConnectionPacket packetReponse = FreeConnectionPacket.CreateFreeConnectionIndicationPacket(connectionPacket.NumeroConnexion, connectionPacket.AdresseDestination, connectionPacket.AdresseSource, Raisons.DistantRefuse); packetEnvoye = packetReponse; EnvoieSystemeBVersLiaison(packetReponse); } else if (!((connectionPacket.AdresseSource % MULTIPLE_POUR_ABSENCE_REPONSE_CONNEXION) == 0)) { ConnectionPacket packetReponse = ConnectionPacket.CreateConnectionConfirmationPacket(connectionPacket.NumeroConnexion, connectionPacket.AdresseDestination, connectionPacket.AdresseSource); packetEnvoye = packetReponse; EnvoieSystemeBVersLiaison(packetReponse); } break; case PacketTypes.DataPacket: if (AquittementNegatif(2)) { } break; } return packetEnvoye; } private bool ConnexionAcceptee(byte adresseSource) { return !((adresseSource % MULTIPLE_POUR_REFUS_CONNEXION_FOURNISSEUR) == 0); } private bool AquittementNegatif(int ps) { Random rand = new Random(); return (ps == rand.Next(0, 7)); } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Main/Reseau/CoucheReseau.cs
C#
asf20
8,197
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Reseau { public partial class Main : Form { public Main() { InitializeComponent(); } //public void WriteLine(string line, RichTextBox rtxt) //{ // rtxt.Text += "\n" + line; // rtxt.ScrollToCaret(); //} //public RichTextBox RichTextBox1 { get { return richTextBox1; } } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Reseau/Main.cs
C#
asf20
604
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Timers; namespace Main.Reseau { public enum EtatsConnexion { ConnexionEtablie, EnAttente } public class Connexion { private static List<Connexion> listeConnexions = new List<Connexion>(); private byte idConnexionLogique; private EtatsConnexion etat; private byte adresseSource; private byte adresseDestination; private int pr; private int ps; private Timer timer; private Connexion(byte adresseSource, byte adresseDestination) { if (listeConnexions.Count > 0) this.idConnexionLogique = (byte)(listeConnexions.Max(c => c.idConnexionLogique) + 1); else this.idConnexionLogique = 1; this.etat = EtatsConnexion.EnAttente; this.adresseSource = adresseSource; this.adresseDestination = adresseDestination; this.pr = 0; this.ps = 0; } public byte IdConnexionLogique { get { return idConnexionLogique; } } public EtatsConnexion Etat { get { return etat; } set { etat = value; } } public byte AdresseSource { get { return adresseSource; } } public byte AdresseDestination { get { return adresseDestination; } } public static List<Connexion> ListeConnexions { get { return listeConnexions.ToList(); } } public static Connexion CreateConnexion(byte adresseSource, byte adresseDestination) { Connexion connexion = new Connexion(adresseSource, adresseDestination); listeConnexions.Add(connexion); return connexion; } public static void DeleteConnexion(Connexion connexion) { listeConnexions.Remove(connexion); } public int GetPS() { if (ps < 8) ps++; else ps = 0; return ps; } public int GetPR() { if (pr < 8) pr++; else pr = 0; return pr; } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Reseau/ConnexionReseau.cs
C#
asf20
2,290
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("Reseau")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Reseau")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("9404171c-6a1e-4f74-b46c-08833bb3d6e1")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Reseau/Properties/AssemblyInfo.cs
C#
asf20
1,545
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Reseau { static class Program { static Main consoleMain; /// <summary> /// Point d'entrée principal de l'application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); consoleMain = new Main(); consoleMain.Show(); //int ctr =0; //while (ctr < 51515151) //{ // consoleMain.WriteLine("awfjnawjfn", consoleMain.RichTextBox1); // ctr++; //} } } }
028490q38u532895uy92hf98jh98shfe98sehgesg
trunk/Reseau/Program.cs
C#
asf20
804
/*! fancyBox v2.0.6 fancyapps.com | fancyapps.com/fancybox/#license */ .fancybox-tmp iframe, .fancybox-tmp object { vertical-align: top; padding: 0; margin: 0; } .fancybox-wrap { position: absolute; top: 0; left: 0; z-index: 8020; } .fancybox-skin { position: relative; padding: 0; margin: 0; background: #f9f9f9; color: #444; text-shadow: none; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .fancybox-opened { z-index: 8030; } .fancybox-opened .fancybox-skin { -webkit-box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5); -moz-box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5); box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5); } .fancybox-outer, .fancybox-inner { padding: 0; margin: 0; position: relative; outline: none; } .fancybox-inner { overflow: hidden; } .fancybox-type-iframe .fancybox-inner { -webkit-overflow-scrolling: touch; } .fancybox-error { color: #444; font: 14px/20px "Helvetica Neue",Helvetica,Arial,sans-serif; margin: 0; padding: 10px; } .fancybox-image, .fancybox-iframe { display: block; width: 100%; height: 100%; border: 0; padding: 0; margin: 0; vertical-align: top; } .fancybox-image { max-width: 100%; max-height: 100%; } #fancybox-loading, .fancybox-close, .fancybox-prev span, .fancybox-next span { background-image: url('http://3.bp.blogspot.com/-d59KQfJPW4U/UqRYyjaTxCI/AAAAAAAAAE0/SZc61lbu1Bg/s1600/fancybox_sprite.png'); } #fancybox-loading { position: fixed; top: 50%; left: 50%; margin-top: -22px; margin-left: -22px; background-position: 0 -108px; opacity: 0.8; cursor: pointer; z-index: 8020; } #fancybox-loading div { width: 44px; height: 44px; background: url('http://3.bp.blogspot.com/-6R6fM22zRjQ/UqRacHvcuaI/AAAAAAAAAFE/E_QZv5Vwhlk/s1600/fancybox_loading.gif') center center no-repeat; } .fancybox-close { position: absolute; top: -18px; right: -18px; width: 36px; height: 36px; cursor: pointer; z-index: 8040; } .fancybox-nav { position: absolute; top: 0; width: 40%; height: 100%; cursor: pointer; background: transparent url('http://1.bp.blogspot.com/-pjEqb5edcB4/UqRaAnjl_2I/AAAAAAAAAE8/1ddyRHfexWI/s1600/blank.gif'); /* helps IE */ -webkit-tap-highlight-color: rgba(0,0,0,0); z-index: 8040; } .fancybox-prev { left: 0; } .fancybox-next { right: 0; } .fancybox-nav span { position: absolute; top: 50%; width: 36px; height: 34px; margin-top: -18px; cursor: pointer; z-index: 8040; visibility: hidden; } .fancybox-prev span { left: 20px; background-position: 0 -36px; } .fancybox-next span { right: 20px; background-position: 0 -72px; } .fancybox-nav:hover span { visibility: visible; } .fancybox-tmp { position: absolute; top: -9999px; left: -9999px; padding: 0; overflow: visible; visibility: hidden; } /* Overlay helper */ #fancybox-overlay { position: absolute; top: 0; left: 0; overflow: hidden; display: none; z-index: 8010; background: #000; } #fancybox-overlay.overlay-fixed { position: fixed; bottom: 0; right: 0; } /* Title helper */ .fancybox-title { visibility: hidden; font: normal 13px/20px "Helvetica Neue",Helvetica,Arial,sans-serif; position: relative; text-shadow: none; z-index: 8050; } .fancybox-opened .fancybox-title { visibility: visible; } .fancybox-title-float-wrap { position: absolute; bottom: 0; right: 50%; margin-bottom: -35px; z-index: 8030; text-align: center; } .fancybox-title-float-wrap .child { display: inline-block; margin-right: -100%; padding: 2px 20px; background: transparent; /* Fallback for web browsers that doesn't support RGBa */ background: rgba(0, 0, 0, 0.8); -webkit-border-radius: 15px; -moz-border-radius: 15px; border-radius: 15px; text-shadow: 0 1px 2px #222; color: #FFF; font-weight: bold; line-height: 24px; white-space: nowrap; } .fancybox-title-outside-wrap { position: relative; margin-top: 10px; color: #fff; } .fancybox-title-inside-wrap { margin-top: 10px; } .fancybox-title-over-wrap { position: absolute; bottom: 0; left: 0; color: #fff; padding: 10px; background: #000; background: rgba(0, 0, 0, .8); }
001easytricks
trunk/fancybox.css
CSS
bsd
4,122
#!/usr/bin/python2.4 # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl except: from cgi import parse_qsl import oauth2 as oauth REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' consumer_key = None consumer_secret = None if consumer_key is None or consumer_secret is None: print 'You need to edit this script and provide values for the' print 'consumer_key and also consumer_secret.' print '' print 'The values you need come from Twitter - you need to register' print 'as a developer your "application". This is needed only until' print 'Twitter finishes the idea they have of a way to allow open-source' print 'based libraries to have a token that can be used to generate a' print 'one-time use key that will allow the library to make the request' print 'on your behalf.' print '' sys.exit(1) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) oauth_client = oauth.Client(oauth_consumer) print 'Requesting temp token from Twitter' resp, content = oauth_client.request(REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': print 'Invalid respond from Twitter requesting temp token: %s' % resp['status'] else: request_token = dict(parse_qsl(content)) print '' print 'Please visit this Twitter page and retrieve the pincode to be used' print 'in the next step to obtaining an Authentication Token:' print '' print '%s?oauth_token=%s' % (AUTHORIZATION_URL, request_token['oauth_token']) print '' pincode = raw_input('Pincode? ') token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(pincode) print '' print 'Generating and signing request for an access token' print '' oauth_client = oauth.Client(oauth_consumer, token) resp, content = oauth_client.request(ACCESS_TOKEN_URL, method='POST', body='oauth_callback=oob&oauth_verifier=%s' % pincode) access_token = dict(parse_qsl(content)) if resp['status'] != '200': print 'The request for a Token did not succeed: %s' % resp['status'] print access_token else: print 'Your Twitter Access Token key: %s' % access_token['oauth_token'] print ' Access Token secret: %s' % access_token['oauth_token_secret'] print ''
123danielbenjaminphilpott-123
get_access_token.py
Python
asf20
3,192
#!/usr/bin/python2.4 # -*- coding: utf-8 -*-# # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''Unit tests for the twitter.py library''' __author__ = 'python-twitter@googlegroups.com' import os import simplejson import time import calendar import unittest import urllib import twitter class StatusTest(unittest.TestCase): SAMPLE_JSON = '''{"created_at": "Fri Jan 26 23:17:14 +0000 2007", "id": 4391023, "text": "A l\u00e9gp\u00e1rn\u00e1s haj\u00f3m tele van angoln\u00e1kkal.", "user": {"description": "Canvas. JC Penny. Three ninety-eight.", "id": 718443, "location": "Okinawa, Japan", "name": "Kesuke Miyagi", "profile_image_url": "https://twitter.com/system/user/profile_image/718443/normal/kesuke.png", "screen_name": "kesuke", "url": "https://twitter.com/kesuke"}}''' def _GetSampleUser(self): return twitter.User(id=718443, name='Kesuke Miyagi', screen_name='kesuke', description=u'Canvas. JC Penny. Three ninety-eight.', location='Okinawa, Japan', url='https://twitter.com/kesuke', profile_image_url='https://twitter.com/system/user/pro' 'file_image/718443/normal/kesuke.pn' 'g') def _GetSampleStatus(self): return twitter.Status(created_at='Fri Jan 26 23:17:14 +0000 2007', id=4391023, text=u'A légpárnás hajóm tele van angolnákkal.', user=self._GetSampleUser()) def testInit(self): '''Test the twitter.Status constructor''' status = twitter.Status(created_at='Fri Jan 26 23:17:14 +0000 2007', id=4391023, text=u'A légpárnás hajóm tele van angolnákkal.', user=self._GetSampleUser()) def testGettersAndSetters(self): '''Test all of the twitter.Status getters and setters''' status = twitter.Status() status.SetId(4391023) self.assertEqual(4391023, status.GetId()) created_at = calendar.timegm((2007, 1, 26, 23, 17, 14, -1, -1, -1)) status.SetCreatedAt('Fri Jan 26 23:17:14 +0000 2007') self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', status.GetCreatedAt()) self.assertEqual(created_at, status.GetCreatedAtInSeconds()) status.SetNow(created_at + 10) self.assertEqual("about 10 seconds ago", status.GetRelativeCreatedAt()) status.SetText(u'A légpárnás hajóm tele van angolnákkal.') self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', status.GetText()) status.SetUser(self._GetSampleUser()) self.assertEqual(718443, status.GetUser().id) def testProperties(self): '''Test all of the twitter.Status properties''' status = twitter.Status() status.id = 1 self.assertEqual(1, status.id) created_at = calendar.timegm((2007, 1, 26, 23, 17, 14, -1, -1, -1)) status.created_at = 'Fri Jan 26 23:17:14 +0000 2007' self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', status.created_at) self.assertEqual(created_at, status.created_at_in_seconds) status.now = created_at + 10 self.assertEqual('about 10 seconds ago', status.relative_created_at) status.user = self._GetSampleUser() self.assertEqual(718443, status.user.id) def _ParseDate(self, string): return calendar.timegm(time.strptime(string, '%b %d %H:%M:%S %Y')) def testRelativeCreatedAt(self): '''Test various permutations of Status relative_created_at''' status = twitter.Status(created_at='Fri Jan 01 12:00:00 +0000 2007') status.now = self._ParseDate('Jan 01 12:00:00 2007') self.assertEqual('about a second ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:00:01 2007') self.assertEqual('about a second ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:00:02 2007') self.assertEqual('about 2 seconds ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:00:05 2007') self.assertEqual('about 5 seconds ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:00:50 2007') self.assertEqual('about a minute ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:01:00 2007') self.assertEqual('about a minute ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:01:10 2007') self.assertEqual('about a minute ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:02:00 2007') self.assertEqual('about 2 minutes ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:31:50 2007') self.assertEqual('about 31 minutes ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:50:00 2007') self.assertEqual('about an hour ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 13:00:00 2007') self.assertEqual('about an hour ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 13:10:00 2007') self.assertEqual('about an hour ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 14:00:00 2007') self.assertEqual('about 2 hours ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 19:00:00 2007') self.assertEqual('about 7 hours ago', status.relative_created_at) status.now = self._ParseDate('Jan 02 11:30:00 2007') self.assertEqual('about a day ago', status.relative_created_at) status.now = self._ParseDate('Jan 04 12:00:00 2007') self.assertEqual('about 3 days ago', status.relative_created_at) status.now = self._ParseDate('Feb 04 12:00:00 2007') self.assertEqual('about 34 days ago', status.relative_created_at) def testAsJsonString(self): '''Test the twitter.Status AsJsonString method''' self.assertEqual(StatusTest.SAMPLE_JSON, self._GetSampleStatus().AsJsonString()) def testAsDict(self): '''Test the twitter.Status AsDict method''' status = self._GetSampleStatus() data = status.AsDict() self.assertEqual(4391023, data['id']) self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', data['created_at']) self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', data['text']) self.assertEqual(718443, data['user']['id']) def testEq(self): '''Test the twitter.Status __eq__ method''' status = twitter.Status() status.created_at = 'Fri Jan 26 23:17:14 +0000 2007' status.id = 4391023 status.text = u'A légpárnás hajóm tele van angolnákkal.' status.user = self._GetSampleUser() self.assertEqual(status, self._GetSampleStatus()) def testNewFromJsonDict(self): '''Test the twitter.Status NewFromJsonDict method''' data = simplejson.loads(StatusTest.SAMPLE_JSON) status = twitter.Status.NewFromJsonDict(data) self.assertEqual(self._GetSampleStatus(), status) class UserTest(unittest.TestCase): SAMPLE_JSON = '''{"description": "Indeterminate things", "id": 673483, "location": "San Francisco, CA", "name": "DeWitt", "profile_image_url": "https://twitter.com/system/user/profile_image/673483/normal/me.jpg", "screen_name": "dewitt", "status": {"created_at": "Fri Jan 26 17:28:19 +0000 2007", "id": 4212713, "text": "\\"Select all\\" and archive your Gmail inbox. The page loads so much faster!"}, "url": "http://unto.net/"}''' def _GetSampleStatus(self): return twitter.Status(created_at='Fri Jan 26 17:28:19 +0000 2007', id=4212713, text='"Select all" and archive your Gmail inbox. ' ' The page loads so much faster!') def _GetSampleUser(self): return twitter.User(id=673483, name='DeWitt', screen_name='dewitt', description=u'Indeterminate things', location='San Francisco, CA', url='http://unto.net/', profile_image_url='https://twitter.com/system/user/prof' 'ile_image/673483/normal/me.jpg', status=self._GetSampleStatus()) def testInit(self): '''Test the twitter.User constructor''' user = twitter.User(id=673483, name='DeWitt', screen_name='dewitt', description=u'Indeterminate things', url='https://twitter.com/dewitt', profile_image_url='https://twitter.com/system/user/prof' 'ile_image/673483/normal/me.jpg', status=self._GetSampleStatus()) def testGettersAndSetters(self): '''Test all of the twitter.User getters and setters''' user = twitter.User() user.SetId(673483) self.assertEqual(673483, user.GetId()) user.SetName('DeWitt') self.assertEqual('DeWitt', user.GetName()) user.SetScreenName('dewitt') self.assertEqual('dewitt', user.GetScreenName()) user.SetDescription('Indeterminate things') self.assertEqual('Indeterminate things', user.GetDescription()) user.SetLocation('San Francisco, CA') self.assertEqual('San Francisco, CA', user.GetLocation()) user.SetProfileImageUrl('https://twitter.com/system/user/profile_im' 'age/673483/normal/me.jpg') self.assertEqual('https://twitter.com/system/user/profile_image/673' '483/normal/me.jpg', user.GetProfileImageUrl()) user.SetStatus(self._GetSampleStatus()) self.assertEqual(4212713, user.GetStatus().id) def testProperties(self): '''Test all of the twitter.User properties''' user = twitter.User() user.id = 673483 self.assertEqual(673483, user.id) user.name = 'DeWitt' self.assertEqual('DeWitt', user.name) user.screen_name = 'dewitt' self.assertEqual('dewitt', user.screen_name) user.description = 'Indeterminate things' self.assertEqual('Indeterminate things', user.description) user.location = 'San Francisco, CA' self.assertEqual('San Francisco, CA', user.location) user.profile_image_url = 'https://twitter.com/system/user/profile_i' \ 'mage/673483/normal/me.jpg' self.assertEqual('https://twitter.com/system/user/profile_image/6734' '83/normal/me.jpg', user.profile_image_url) self.status = self._GetSampleStatus() self.assertEqual(4212713, self.status.id) def testAsJsonString(self): '''Test the twitter.User AsJsonString method''' self.assertEqual(UserTest.SAMPLE_JSON, self._GetSampleUser().AsJsonString()) def testAsDict(self): '''Test the twitter.User AsDict method''' user = self._GetSampleUser() data = user.AsDict() self.assertEqual(673483, data['id']) self.assertEqual('DeWitt', data['name']) self.assertEqual('dewitt', data['screen_name']) self.assertEqual('Indeterminate things', data['description']) self.assertEqual('San Francisco, CA', data['location']) self.assertEqual('https://twitter.com/system/user/profile_image/6734' '83/normal/me.jpg', data['profile_image_url']) self.assertEqual('http://unto.net/', data['url']) self.assertEqual(4212713, data['status']['id']) def testEq(self): '''Test the twitter.User __eq__ method''' user = twitter.User() user.id = 673483 user.name = 'DeWitt' user.screen_name = 'dewitt' user.description = 'Indeterminate things' user.location = 'San Francisco, CA' user.profile_image_url = 'https://twitter.com/system/user/profile_image/67' \ '3483/normal/me.jpg' user.url = 'http://unto.net/' user.status = self._GetSampleStatus() self.assertEqual(user, self._GetSampleUser()) def testNewFromJsonDict(self): '''Test the twitter.User NewFromJsonDict method''' data = simplejson.loads(UserTest.SAMPLE_JSON) user = twitter.User.NewFromJsonDict(data) self.assertEqual(self._GetSampleUser(), user) class TrendTest(unittest.TestCase): SAMPLE_JSON = '''{"name": "Kesuke Miyagi", "query": "Kesuke Miyagi"}''' def _GetSampleTrend(self): return twitter.Trend(name='Kesuke Miyagi', query='Kesuke Miyagi', timestamp='Fri Jan 26 23:17:14 +0000 2007') def testInit(self): '''Test the twitter.Trend constructor''' trend = twitter.Trend(name='Kesuke Miyagi', query='Kesuke Miyagi', timestamp='Fri Jan 26 23:17:14 +0000 2007') def testProperties(self): '''Test all of the twitter.Trend properties''' trend = twitter.Trend() trend.name = 'Kesuke Miyagi' self.assertEqual('Kesuke Miyagi', trend.name) trend.query = 'Kesuke Miyagi' self.assertEqual('Kesuke Miyagi', trend.query) trend.timestamp = 'Fri Jan 26 23:17:14 +0000 2007' self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', trend.timestamp) def testNewFromJsonDict(self): '''Test the twitter.Trend NewFromJsonDict method''' data = simplejson.loads(TrendTest.SAMPLE_JSON) trend = twitter.Trend.NewFromJsonDict(data, timestamp='Fri Jan 26 23:17:14 +0000 2007') self.assertEqual(self._GetSampleTrend(), trend) def testEq(self): '''Test the twitter.Trend __eq__ method''' trend = twitter.Trend() trend.name = 'Kesuke Miyagi' trend.query = 'Kesuke Miyagi' trend.timestamp = 'Fri Jan 26 23:17:14 +0000 2007' self.assertEqual(trend, self._GetSampleTrend()) class FileCacheTest(unittest.TestCase): def testInit(self): """Test the twitter._FileCache constructor""" cache = twitter._FileCache() self.assert_(cache is not None, 'cache is None') def testSet(self): """Test the twitter._FileCache.Set method""" cache = twitter._FileCache() cache.Set("foo",'Hello World!') cache.Remove("foo") def testRemove(self): """Test the twitter._FileCache.Remove method""" cache = twitter._FileCache() cache.Set("foo",'Hello World!') cache.Remove("foo") data = cache.Get("foo") self.assertEqual(data, None, 'data is not None') def testGet(self): """Test the twitter._FileCache.Get method""" cache = twitter._FileCache() cache.Set("foo",'Hello World!') data = cache.Get("foo") self.assertEqual('Hello World!', data) cache.Remove("foo") def testGetCachedTime(self): """Test the twitter._FileCache.GetCachedTime method""" now = time.time() cache = twitter._FileCache() cache.Set("foo",'Hello World!') cached_time = cache.GetCachedTime("foo") delta = cached_time - now self.assert_(delta <= 1, 'Cached time differs from clock time by more than 1 second.') cache.Remove("foo") class ApiTest(unittest.TestCase): def setUp(self): self._urllib = MockUrllib() api = twitter.Api(consumer_key='CONSUMER_KEY', consumer_secret='CONSUMER_SECRET', access_token_key='OAUTH_TOKEN', access_token_secret='OAUTH_SECRET', cache=None) api.SetUrllib(self._urllib) self._api = api def testTwitterError(self): '''Test that twitter responses containing an error message are wrapped.''' self._AddHandler('https://api.twitter.com/1/statuses/user_timeline.json', curry(self._OpenTestData, 'public_timeline_error.json')) # Manually try/catch so we can check the exception's value try: statuses = self._api.GetUserTimeline() except twitter.TwitterError, error: # If the error message matches, the test passes self.assertEqual('test error', error.message) else: self.fail('TwitterError expected') def testGetUserTimeline(self): '''Test the twitter.Api GetUserTimeline method''' self._AddHandler('https://api.twitter.com/1/statuses/user_timeline/kesuke.json?count=1', curry(self._OpenTestData, 'user_timeline-kesuke.json')) statuses = self._api.GetUserTimeline('kesuke', count=1) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(89512102, statuses[0].id) self.assertEqual(718443, statuses[0].user.id) def testGetFriendsTimeline(self): '''Test the twitter.Api GetFriendsTimeline method''' self._AddHandler('https://api.twitter.com/1/statuses/friends_timeline/kesuke.json', curry(self._OpenTestData, 'friends_timeline-kesuke.json')) statuses = self._api.GetFriendsTimeline('kesuke') # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(20, len(statuses)) self.assertEqual(718443, statuses[0].user.id) def testGetStatus(self): '''Test the twitter.Api GetStatus method''' self._AddHandler('https://api.twitter.com/1/statuses/show/89512102.json', curry(self._OpenTestData, 'show-89512102.json')) status = self._api.GetStatus(89512102) self.assertEqual(89512102, status.id) self.assertEqual(718443, status.user.id) def testDestroyStatus(self): '''Test the twitter.Api DestroyStatus method''' self._AddHandler('https://api.twitter.com/1/statuses/destroy/103208352.json', curry(self._OpenTestData, 'status-destroy.json')) status = self._api.DestroyStatus(103208352) self.assertEqual(103208352, status.id) def testPostUpdate(self): '''Test the twitter.Api PostUpdate method''' self._AddHandler('https://api.twitter.com/1/statuses/update.json', curry(self._OpenTestData, 'update.json')) status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей'.encode('utf8')) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text) def testPostUpdateLatLon(self): '''Test the twitter.Api PostUpdate method, when used in conjunction with latitude and longitude''' self._AddHandler('https://api.twitter.com/1/statuses/update.json', curry(self._OpenTestData, 'update_latlong.json')) #test another update with geo parameters, again test somewhat arbitrary status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей'.encode('utf8'), latitude=54.2, longitude=-2) self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text) self.assertEqual(u'Point',status.GetGeo()['type']) self.assertEqual(26.2,status.GetGeo()['coordinates'][0]) self.assertEqual(127.5,status.GetGeo()['coordinates'][1]) def testGetReplies(self): '''Test the twitter.Api GetReplies method''' self._AddHandler('https://api.twitter.com/1/statuses/replies.json?page=1', curry(self._OpenTestData, 'replies.json')) statuses = self._api.GetReplies(page=1) self.assertEqual(36657062, statuses[0].id) def testGetRetweetsOfMe(self): '''Test the twitter.API GetRetweetsOfMe method''' self._AddHandler('https://api.twitter.com/1/statuses/retweets_of_me.json', curry(self._OpenTestData, 'retweets_of_me.json')) retweets = self._api.GetRetweetsOfMe() self.assertEqual(253650670274637824, retweets[0].id) def testGetFriends(self): '''Test the twitter.Api GetFriends method''' self._AddHandler('https://api.twitter.com/1/statuses/friends.json?cursor=123', curry(self._OpenTestData, 'friends.json')) users = self._api.GetFriends(cursor=123) buzz = [u.status for u in users if u.screen_name == 'buzz'] self.assertEqual(89543882, buzz[0].id) def testGetFollowers(self): '''Test the twitter.Api GetFollowers method''' self._AddHandler('https://api.twitter.com/1/statuses/followers.json?cursor=-1', curry(self._OpenTestData, 'followers.json')) users = self._api.GetFollowers() # This is rather arbitrary, but spot checking is better than nothing alexkingorg = [u.status for u in users if u.screen_name == 'alexkingorg'] self.assertEqual(89554432, alexkingorg[0].id) def testGetFeatured(self): '''Test the twitter.Api GetFeatured method''' self._AddHandler('https://api.twitter.com/1/statuses/featured.json', curry(self._OpenTestData, 'featured.json')) users = self._api.GetFeatured() # This is rather arbitrary, but spot checking is better than nothing stevenwright = [u.status for u in users if u.screen_name == 'stevenwright'] self.assertEqual(86991742, stevenwright[0].id) def testGetDirectMessages(self): '''Test the twitter.Api GetDirectMessages method''' self._AddHandler('https://api.twitter.com/1/direct_messages.json?page=1', curry(self._OpenTestData, 'direct_messages.json')) statuses = self._api.GetDirectMessages(page=1) self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', statuses[0].text) def testPostDirectMessage(self): '''Test the twitter.Api PostDirectMessage method''' self._AddHandler('https://api.twitter.com/1/direct_messages/new.json', curry(self._OpenTestData, 'direct_messages-new.json')) status = self._api.PostDirectMessage('test', u'Моё судно на воздушной подушке полно угрей'.encode('utf8')) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text) def testDestroyDirectMessage(self): '''Test the twitter.Api DestroyDirectMessage method''' self._AddHandler('https://api.twitter.com/1/direct_messages/destroy/3496342.json', curry(self._OpenTestData, 'direct_message-destroy.json')) status = self._api.DestroyDirectMessage(3496342) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(673483, status.sender_id) def testCreateFriendship(self): '''Test the twitter.Api CreateFriendship method''' self._AddHandler('https://api.twitter.com/1/friendships/create/dewitt.json', curry(self._OpenTestData, 'friendship-create.json')) user = self._api.CreateFriendship('dewitt') # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(673483, user.id) def testDestroyFriendship(self): '''Test the twitter.Api DestroyFriendship method''' self._AddHandler('https://api.twitter.com/1/friendships/destroy/dewitt.json', curry(self._OpenTestData, 'friendship-destroy.json')) user = self._api.DestroyFriendship('dewitt') # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(673483, user.id) def testGetUser(self): '''Test the twitter.Api GetUser method''' self._AddHandler('https://api.twitter.com/1/users/show/dewitt.json', curry(self._OpenTestData, 'show-dewitt.json')) user = self._api.GetUser('dewitt') self.assertEqual('dewitt', user.screen_name) self.assertEqual(89586072, user.status.id) def _AddHandler(self, url, callback): self._urllib.AddHandler(url, callback) def _GetTestDataPath(self, filename): directory = os.path.dirname(os.path.abspath(__file__)) test_data_dir = os.path.join(directory, 'testdata') return os.path.join(test_data_dir, filename) def _OpenTestData(self, filename): f = open(self._GetTestDataPath(filename)) # make sure that the returned object contains an .info() method: # headers are set to {} return urllib.addinfo(f, {}) class MockUrllib(object): '''A mock replacement for urllib that hardcodes specific responses.''' def __init__(self): self._handlers = {} self.HTTPBasicAuthHandler = MockHTTPBasicAuthHandler def AddHandler(self, url, callback): self._handlers[url] = callback def build_opener(self, *handlers): return MockOpener(self._handlers) def HTTPHandler(self, *args, **kwargs): return None def HTTPSHandler(self, *args, **kwargs): return None def OpenerDirector(self): return self.build_opener() def ProxyHandler(self,*args,**kwargs): return None class MockOpener(object): '''A mock opener for urllib''' def __init__(self, handlers): self._handlers = handlers self._opened = False def open(self, url, data=None): if self._opened: raise Exception('MockOpener already opened.') # Remove parameters from URL - they're only added by oauth and we # don't want to test oauth if '?' in url: # We split using & and filter on the beginning of each key # This is crude but we have to keep the ordering for now (url, qs) = url.split('?') tokens = [token for token in qs.split('&') if not token.startswith('oauth')] if len(tokens) > 0: url = "%s?%s"%(url, '&'.join(tokens)) if url in self._handlers: self._opened = True return self._handlers[url]() else: raise Exception('Unexpected URL %s (Checked: %s)' % (url, self._handlers)) def add_handler(self, *args, **kwargs): pass def close(self): if not self._opened: raise Exception('MockOpener closed before it was opened.') self._opened = False class MockHTTPBasicAuthHandler(object): '''A mock replacement for HTTPBasicAuthHandler''' def add_password(self, realm, uri, user, passwd): # TODO(dewitt): Add verification that the proper args are passed pass class curry: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 def __init__(self, fun, *args, **kwargs): self.fun = fun self.pending = args[:] self.kwargs = kwargs.copy() def __call__(self, *args, **kwargs): if kwargs and self.kwargs: kw = self.kwargs.copy() kw.update(kwargs) else: kw = kwargs or self.kwargs return self.fun(*(self.pending + args), **kw) def suite(): suite = unittest.TestSuite() suite.addTests(unittest.makeSuite(FileCacheTest)) suite.addTests(unittest.makeSuite(StatusTest)) suite.addTests(unittest.makeSuite(UserTest)) suite.addTests(unittest.makeSuite(ApiTest)) return suite if __name__ == '__main__': unittest.main()
123danielbenjaminphilpott-123
twitter_test.py
Python
asf20
27,102
#!/usr/bin/python2.4 '''Load the latest update for a Twitter user and leave it in an XHTML fragment''' __author__ = 'dewitt@google.com' import codecs import getopt import sys import twitter TEMPLATE = """ <div class="twitter"> <span class="twitter-user"><a href="http://twitter.com/%s">Twitter</a>: </span> <span class="twitter-text">%s</span> <span class="twitter-relative-created-at"><a href="http://twitter.com/%s/statuses/%s">Posted %s</a></span> </div> """ def Usage(): print 'Usage: %s [options] twitterid' % __file__ print print ' This script fetches a users latest twitter update and stores' print ' the result in a file as an XHTML fragment' print print ' Options:' print ' --help -h : print this help' print ' --output : the output file [default: stdout]' def FetchTwitter(user, output): assert user statuses = twitter.Api().GetUserTimeline(user=user, count=1) s = statuses[0] xhtml = TEMPLATE % (s.user.screen_name, s.text, s.user.screen_name, s.id, s.relative_created_at) if output: Save(xhtml, output) else: print xhtml def Save(xhtml, output): out = codecs.open(output, mode='w', encoding='ascii', errors='xmlcharrefreplace') out.write(xhtml) out.close() def main(): try: opts, args = getopt.gnu_getopt(sys.argv[1:], 'ho', ['help', 'output=']) except getopt.GetoptError: Usage() sys.exit(2) try: user = args[0] except: Usage() sys.exit(2) output = None for o, a in opts: if o in ("-h", "--help"): Usage() sys.exit(2) if o in ("-o", "--output"): output = a FetchTwitter(user, output) if __name__ == "__main__": main()
123danielbenjaminphilpott-123
examples/twitter-to-xhtml.py
Python
asf20
1,685
#!/usr/bin/python2.4 '''Post a message to twitter''' __author__ = 'dewitt@google.com' import ConfigParser import getopt import os import sys import twitter USAGE = '''Usage: tweet [options] message This script posts a message to Twitter. Options: -h --help : print this help --consumer-key : the twitter consumer key --consumer-secret : the twitter consumer secret --access-key : the twitter access token key --access-secret : the twitter access token secret --encoding : the character set encoding used in input strings, e.g. "utf-8". [optional] Documentation: If either of the command line flags are not present, the environment variables TWEETUSERNAME and TWEETPASSWORD will then be checked for your consumer_key or consumer_secret, respectively. If neither the command line flags nor the enviroment variables are present, the .tweetrc file, if it exists, can be used to set the default consumer_key and consumer_secret. The file should contain the following three lines, replacing *consumer_key* with your consumer key, and *consumer_secret* with your consumer secret: A skeletal .tweetrc file: [Tweet] consumer_key: *consumer_key* consumer_secret: *consumer_password* access_key: *access_key* access_secret: *access_password* ''' def PrintUsageAndExit(): print USAGE sys.exit(2) def GetConsumerKeyEnv(): return os.environ.get("TWEETUSERNAME", None) def GetConsumerSecretEnv(): return os.environ.get("TWEETPASSWORD", None) def GetAccessKeyEnv(): return os.environ.get("TWEETACCESSKEY", None) def GetAccessSecretEnv(): return os.environ.get("TWEETACCESSSECRET", None) class TweetRc(object): def __init__(self): self._config = None def GetConsumerKey(self): return self._GetOption('consumer_key') def GetConsumerSecret(self): return self._GetOption('consumer_secret') def GetAccessKey(self): return self._GetOption('access_key') def GetAccessSecret(self): return self._GetOption('access_secret') def _GetOption(self, option): try: return self._GetConfig().get('Tweet', option) except: return None def _GetConfig(self): if not self._config: self._config = ConfigParser.ConfigParser() self._config.read(os.path.expanduser('~/.tweetrc')) return self._config def main(): try: shortflags = 'h' longflags = ['help', 'consumer-key=', 'consumer-secret=', 'access-key=', 'access-secret=', 'encoding='] opts, args = getopt.gnu_getopt(sys.argv[1:], shortflags, longflags) except getopt.GetoptError: PrintUsageAndExit() consumer_keyflag = None consumer_secretflag = None access_keyflag = None access_secretflag = None encoding = None for o, a in opts: if o in ("-h", "--help"): PrintUsageAndExit() if o in ("--consumer-key"): consumer_keyflag = a if o in ("--consumer-secret"): consumer_secretflag = a if o in ("--access-key"): access_keyflag = a if o in ("--access-secret"): access_secretflag = a if o in ("--encoding"): encoding = a message = ' '.join(args) if not message: PrintUsageAndExit() rc = TweetRc() consumer_key = consumer_keyflag or GetConsumerKeyEnv() or rc.GetConsumerKey() consumer_secret = consumer_secretflag or GetConsumerSecretEnv() or rc.GetConsumerSecret() access_key = access_keyflag or GetAccessKeyEnv() or rc.GetAccessKey() access_secret = access_secretflag or GetAccessSecretEnv() or rc.GetAccessSecret() if not consumer_key or not consumer_secret or not access_key or not access_secret: PrintUsageAndExit() api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_key, access_token_secret=access_secret, input_encoding=encoding) try: status = api.PostUpdate(message) except UnicodeDecodeError: print "Your message could not be encoded. Perhaps it contains non-ASCII characters? " print "Try explicitly specifying the encoding with the --encoding flag" sys.exit(2) print "%s just posted: %s" % (status.user.name, status.text) if __name__ == "__main__": main()
123danielbenjaminphilpott-123
examples/tweet.py
Python
asf20
4,205
#!/usr/bin/python2.4 # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''A class that defines the default URL Shortener. TinyURL is provided as the default and as an example. ''' import urllib # Change History # # 2010-05-16 # TinyURL example and the idea for this comes from a bug filed by # acolorado with patch provided by ghills. Class implementation # was done by bear. # # Issue 19 http://code.google.com/p/python-twitter/issues/detail?id=19 # class ShortenURL(object): '''Helper class to make URL Shortener calls if/when required''' def __init__(self, userid=None, password=None): '''Instantiate a new ShortenURL object Args: userid: userid for any required authorization call [optional] password: password for any required authorization call [optional] ''' self.userid = userid self.password = password def Shorten(self, longURL): '''Call TinyURL API and returned shortened URL result Args: longURL: URL string to shorten Returns: The shortened URL as a string Note: longURL is required and no checks are made to ensure completeness ''' result = None f = urllib.urlopen("http://tinyurl.com/api-create.php?url=%s" % longURL) try: result = f.read() finally: f.close() return result
123danielbenjaminphilpott-123
examples/shorten_url.py
Python
asf20
2,072
#!/usr/bin/python2.4 # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''The setup and build script for the python-twitter library.''' __author__ = 'python-twitter@googlegroups.com' __version__ = '0.8.5' # The base package metadata to be used by both distutils and setuptools METADATA = dict( name = "python-twitter", version = __version__, py_modules = ['twitter'], author='The Python-Twitter Developers', author_email='python-twitter@googlegroups.com', description='A python wrapper around the Twitter API', license='Apache License 2.0', url='https://github.com/bear/python-twitter', keywords='twitter api', ) # Extra package metadata to be used only if setuptools is installed SETUPTOOLS_METADATA = dict( install_requires = ['setuptools', 'simplejson', 'oauth2'], include_package_data = True, classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Communications :: Chat', 'Topic :: Internet', ], test_suite = 'twitter_test.suite', ) def Read(file): return open(file).read() def BuildLongDescription(): return '\n'.join([Read('README.md'), Read('CHANGES')]) def Main(): # Build the long_description from the README and CHANGES METADATA['long_description'] = BuildLongDescription() # Use setuptools if available, otherwise fallback and use distutils try: import setuptools METADATA.update(SETUPTOOLS_METADATA) setuptools.setup(**METADATA) except ImportError: import distutils.core distutils.core.setup(**METADATA) if __name__ == '__main__': Main()
123danielbenjaminphilpott-123
setup.py
Python
asf20
2,254
#include "Python.h" #include "structmember.h" #if PY_VERSION_HEX < 0x02060000 && !defined(Py_TYPE) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #endif #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PyInt_FromSsize_t PyInt_FromLong #define PyInt_AsSsize_t PyInt_AsLong #endif #ifndef Py_IS_FINITE #define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X)) #endif #ifdef __GNUC__ #define UNUSED __attribute__((__unused__)) #else #define UNUSED #endif #define DEFAULT_ENCODING "utf-8" #define PyScanner_Check(op) PyObject_TypeCheck(op, &PyScannerType) #define PyScanner_CheckExact(op) (Py_TYPE(op) == &PyScannerType) #define PyEncoder_Check(op) PyObject_TypeCheck(op, &PyEncoderType) #define PyEncoder_CheckExact(op) (Py_TYPE(op) == &PyEncoderType) static PyTypeObject PyScannerType; static PyTypeObject PyEncoderType; typedef struct _PyScannerObject { PyObject_HEAD PyObject *encoding; PyObject *strict; PyObject *object_hook; PyObject *parse_float; PyObject *parse_int; PyObject *parse_constant; } PyScannerObject; static PyMemberDef scanner_members[] = { {"encoding", T_OBJECT, offsetof(PyScannerObject, encoding), READONLY, "encoding"}, {"strict", T_OBJECT, offsetof(PyScannerObject, strict), READONLY, "strict"}, {"object_hook", T_OBJECT, offsetof(PyScannerObject, object_hook), READONLY, "object_hook"}, {"parse_float", T_OBJECT, offsetof(PyScannerObject, parse_float), READONLY, "parse_float"}, {"parse_int", T_OBJECT, offsetof(PyScannerObject, parse_int), READONLY, "parse_int"}, {"parse_constant", T_OBJECT, offsetof(PyScannerObject, parse_constant), READONLY, "parse_constant"}, {NULL} }; typedef struct _PyEncoderObject { PyObject_HEAD PyObject *markers; PyObject *defaultfn; PyObject *encoder; PyObject *indent; PyObject *key_separator; PyObject *item_separator; PyObject *sort_keys; PyObject *skipkeys; int fast_encode; int allow_nan; } PyEncoderObject; static PyMemberDef encoder_members[] = { {"markers", T_OBJECT, offsetof(PyEncoderObject, markers), READONLY, "markers"}, {"default", T_OBJECT, offsetof(PyEncoderObject, defaultfn), READONLY, "default"}, {"encoder", T_OBJECT, offsetof(PyEncoderObject, encoder), READONLY, "encoder"}, {"indent", T_OBJECT, offsetof(PyEncoderObject, indent), READONLY, "indent"}, {"key_separator", T_OBJECT, offsetof(PyEncoderObject, key_separator), READONLY, "key_separator"}, {"item_separator", T_OBJECT, offsetof(PyEncoderObject, item_separator), READONLY, "item_separator"}, {"sort_keys", T_OBJECT, offsetof(PyEncoderObject, sort_keys), READONLY, "sort_keys"}, {"skipkeys", T_OBJECT, offsetof(PyEncoderObject, skipkeys), READONLY, "skipkeys"}, {NULL} }; static Py_ssize_t ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars); static PyObject * ascii_escape_unicode(PyObject *pystr); static PyObject * ascii_escape_str(PyObject *pystr); static PyObject * py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr); void init_speedups(void); static PyObject * scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr); static PyObject * scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr); static PyObject * _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx); static int scanner_init(PyObject *self, PyObject *args, PyObject *kwds); static void scanner_dealloc(PyObject *self); static int encoder_init(PyObject *self, PyObject *args, PyObject *kwds); static void encoder_dealloc(PyObject *self); static int encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level); static int encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level); static int encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level); static PyObject * _encoded_const(PyObject *const); static void raise_errmsg(char *msg, PyObject *s, Py_ssize_t end); static PyObject * encoder_encode_string(PyEncoderObject *s, PyObject *obj); static int _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr); static PyObject * _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr); static PyObject * encoder_encode_float(PyEncoderObject *s, PyObject *obj); #define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"') #define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r')) #define MIN_EXPANSION 6 #ifdef Py_UNICODE_WIDE #define MAX_EXPANSION (2 * MIN_EXPANSION) #else #define MAX_EXPANSION MIN_EXPANSION #endif static int _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr) { /* PyObject to Py_ssize_t converter */ *size_ptr = PyInt_AsSsize_t(o); if (*size_ptr == -1 && PyErr_Occurred()); return 1; return 0; } static PyObject * _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr) { /* Py_ssize_t to PyObject converter */ return PyInt_FromSsize_t(*size_ptr); } static Py_ssize_t ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars) { /* Escape unicode code point c to ASCII escape sequences in char *output. output must have at least 12 bytes unused to accommodate an escaped surrogate pair "\uXXXX\uXXXX" */ output[chars++] = '\\'; switch (c) { case '\\': output[chars++] = (char)c; break; case '"': output[chars++] = (char)c; break; case '\b': output[chars++] = 'b'; break; case '\f': output[chars++] = 'f'; break; case '\n': output[chars++] = 'n'; break; case '\r': output[chars++] = 'r'; break; case '\t': output[chars++] = 't'; break; default: #ifdef Py_UNICODE_WIDE if (c >= 0x10000) { /* UTF-16 surrogate pair */ Py_UNICODE v = c - 0x10000; c = 0xd800 | ((v >> 10) & 0x3ff); output[chars++] = 'u'; output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf]; output[chars++] = "0123456789abcdef"[(c ) & 0xf]; c = 0xdc00 | (v & 0x3ff); output[chars++] = '\\'; } #endif output[chars++] = 'u'; output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf]; output[chars++] = "0123456789abcdef"[(c ) & 0xf]; } return chars; } static PyObject * ascii_escape_unicode(PyObject *pystr) { /* Take a PyUnicode pystr and return a new ASCII-only escaped PyString */ Py_ssize_t i; Py_ssize_t input_chars; Py_ssize_t output_size; Py_ssize_t max_output_size; Py_ssize_t chars; PyObject *rval; char *output; Py_UNICODE *input_unicode; input_chars = PyUnicode_GET_SIZE(pystr); input_unicode = PyUnicode_AS_UNICODE(pystr); /* One char input can be up to 6 chars output, estimate 4 of these */ output_size = 2 + (MIN_EXPANSION * 4) + input_chars; max_output_size = 2 + (input_chars * MAX_EXPANSION); rval = PyString_FromStringAndSize(NULL, output_size); if (rval == NULL) { return NULL; } output = PyString_AS_STRING(rval); chars = 0; output[chars++] = '"'; for (i = 0; i < input_chars; i++) { Py_UNICODE c = input_unicode[i]; if (S_CHAR(c)) { output[chars++] = (char)c; } else { chars = ascii_escape_char(c, output, chars); } if (output_size - chars < (1 + MAX_EXPANSION)) { /* There's more than four, so let's resize by a lot */ Py_ssize_t new_output_size = output_size * 2; /* This is an upper bound */ if (new_output_size > max_output_size) { new_output_size = max_output_size; } /* Make sure that the output size changed before resizing */ if (new_output_size != output_size) { output_size = new_output_size; if (_PyString_Resize(&rval, output_size) == -1) { return NULL; } output = PyString_AS_STRING(rval); } } } output[chars++] = '"'; if (_PyString_Resize(&rval, chars) == -1) { return NULL; } return rval; } static PyObject * ascii_escape_str(PyObject *pystr) { /* Take a PyString pystr and return a new ASCII-only escaped PyString */ Py_ssize_t i; Py_ssize_t input_chars; Py_ssize_t output_size; Py_ssize_t chars; PyObject *rval; char *output; char *input_str; input_chars = PyString_GET_SIZE(pystr); input_str = PyString_AS_STRING(pystr); /* Fast path for a string that's already ASCII */ for (i = 0; i < input_chars; i++) { Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i]; if (!S_CHAR(c)) { /* If we have to escape something, scan the string for unicode */ Py_ssize_t j; for (j = i; j < input_chars; j++) { c = (Py_UNICODE)(unsigned char)input_str[j]; if (c > 0x7f) { /* We hit a non-ASCII character, bail to unicode mode */ PyObject *uni; uni = PyUnicode_DecodeUTF8(input_str, input_chars, "strict"); if (uni == NULL) { return NULL; } rval = ascii_escape_unicode(uni); Py_DECREF(uni); return rval; } } break; } } if (i == input_chars) { /* Input is already ASCII */ output_size = 2 + input_chars; } else { /* One char input can be up to 6 chars output, estimate 4 of these */ output_size = 2 + (MIN_EXPANSION * 4) + input_chars; } rval = PyString_FromStringAndSize(NULL, output_size); if (rval == NULL) { return NULL; } output = PyString_AS_STRING(rval); output[0] = '"'; /* We know that everything up to i is ASCII already */ chars = i + 1; memcpy(&output[1], input_str, i); for (; i < input_chars; i++) { Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i]; if (S_CHAR(c)) { output[chars++] = (char)c; } else { chars = ascii_escape_char(c, output, chars); } /* An ASCII char can't possibly expand to a surrogate! */ if (output_size - chars < (1 + MIN_EXPANSION)) { /* There's more than four, so let's resize by a lot */ output_size *= 2; if (output_size > 2 + (input_chars * MIN_EXPANSION)) { output_size = 2 + (input_chars * MIN_EXPANSION); } if (_PyString_Resize(&rval, output_size) == -1) { return NULL; } output = PyString_AS_STRING(rval); } } output[chars++] = '"'; if (_PyString_Resize(&rval, chars) == -1) { return NULL; } return rval; } static void raise_errmsg(char *msg, PyObject *s, Py_ssize_t end) { /* Use the Python function simplejson.decoder.errmsg to raise a nice looking ValueError exception */ static PyObject *errmsg_fn = NULL; PyObject *pymsg; if (errmsg_fn == NULL) { PyObject *decoder = PyImport_ImportModule("simplejson.decoder"); if (decoder == NULL) return; errmsg_fn = PyObject_GetAttrString(decoder, "errmsg"); Py_DECREF(decoder); if (errmsg_fn == NULL) return; } pymsg = PyObject_CallFunction(errmsg_fn, "(zOO&)", msg, s, _convertPyInt_FromSsize_t, &end); if (pymsg) { PyErr_SetObject(PyExc_ValueError, pymsg); Py_DECREF(pymsg); } } static PyObject * join_list_unicode(PyObject *lst) { /* return u''.join(lst) */ static PyObject *joinfn = NULL; if (joinfn == NULL) { PyObject *ustr = PyUnicode_FromUnicode(NULL, 0); if (ustr == NULL) return NULL; joinfn = PyObject_GetAttrString(ustr, "join"); Py_DECREF(ustr); if (joinfn == NULL) return NULL; } return PyObject_CallFunctionObjArgs(joinfn, lst, NULL); } static PyObject * join_list_string(PyObject *lst) { /* return ''.join(lst) */ static PyObject *joinfn = NULL; if (joinfn == NULL) { PyObject *ustr = PyString_FromStringAndSize(NULL, 0); if (ustr == NULL) return NULL; joinfn = PyObject_GetAttrString(ustr, "join"); Py_DECREF(ustr); if (joinfn == NULL) return NULL; } return PyObject_CallFunctionObjArgs(joinfn, lst, NULL); } static PyObject * _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) { /* return (rval, idx) tuple, stealing reference to rval */ PyObject *tpl; PyObject *pyidx; /* steal a reference to rval, returns (rval, idx) */ if (rval == NULL) { return NULL; } pyidx = PyInt_FromSsize_t(idx); if (pyidx == NULL) { Py_DECREF(rval); return NULL; } tpl = PyTuple_New(2); if (tpl == NULL) { Py_DECREF(pyidx); Py_DECREF(rval); return NULL; } PyTuple_SET_ITEM(tpl, 0, rval); PyTuple_SET_ITEM(tpl, 1, pyidx); return tpl; } static PyObject * scanstring_str(PyObject *pystr, Py_ssize_t end, char *encoding, int strict, Py_ssize_t *next_end_ptr) { /* Read the JSON string from PyString pystr. end is the index of the first character after the quote. encoding is the encoding of pystr (must be an ASCII superset) if strict is zero then literal control characters are allowed *next_end_ptr is a return-by-reference index of the character after the end quote Return value is a new PyString (if ASCII-only) or PyUnicode */ PyObject *rval; Py_ssize_t len = PyString_GET_SIZE(pystr); Py_ssize_t begin = end - 1; Py_ssize_t next = begin; int has_unicode = 0; char *buf = PyString_AS_STRING(pystr); PyObject *chunks = PyList_New(0); if (chunks == NULL) { goto bail; } if (end < 0 || len <= end) { PyErr_SetString(PyExc_ValueError, "end is out of bounds"); goto bail; } while (1) { /* Find the end of the string or the next escape */ Py_UNICODE c = 0; PyObject *chunk = NULL; for (next = end; next < len; next++) { c = (unsigned char)buf[next]; if (c == '"' || c == '\\') { break; } else if (strict && c <= 0x1f) { raise_errmsg("Invalid control character at", pystr, next); goto bail; } else if (c > 0x7f) { has_unicode = 1; } } if (!(c == '"' || c == '\\')) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } /* Pick up this chunk if it's not zero length */ if (next != end) { PyObject *strchunk = PyString_FromStringAndSize(&buf[end], next - end); if (strchunk == NULL) { goto bail; } if (has_unicode) { chunk = PyUnicode_FromEncodedObject(strchunk, encoding, NULL); Py_DECREF(strchunk); if (chunk == NULL) { goto bail; } } else { chunk = strchunk; } if (PyList_Append(chunks, chunk)) { Py_DECREF(chunk); goto bail; } Py_DECREF(chunk); } next++; if (c == '"') { end = next; break; } if (next == len) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } c = buf[next]; if (c != 'u') { /* Non-unicode backslash escapes */ end = next + 1; switch (c) { case '"': break; case '\\': break; case '/': break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; default: c = 0; } if (c == 0) { raise_errmsg("Invalid \\escape", pystr, end - 2); goto bail; } } else { c = 0; next++; end = next + 4; if (end >= len) { raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1); goto bail; } /* Decode 4 hex digits */ for (; next < end; next++) { Py_UNICODE digit = buf[next]; c <<= 4; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } #ifdef Py_UNICODE_WIDE /* Surrogate pair */ if ((c & 0xfc00) == 0xd800) { Py_UNICODE c2 = 0; if (end + 6 >= len) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } if (buf[next++] != '\\' || buf[next++] != 'u') { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } end += 6; /* Decode 4 hex digits */ for (; next < end; next++) { c2 <<= 4; Py_UNICODE digit = buf[next]; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c2 |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c2 |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c2 |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } if ((c2 & 0xfc00) != 0xdc00) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00)); } else if ((c & 0xfc00) == 0xdc00) { raise_errmsg("Unpaired low surrogate", pystr, end - 5); goto bail; } #endif } if (c > 0x7f) { has_unicode = 1; } if (has_unicode) { chunk = PyUnicode_FromUnicode(&c, 1); if (chunk == NULL) { goto bail; } } else { char c_char = Py_CHARMASK(c); chunk = PyString_FromStringAndSize(&c_char, 1); if (chunk == NULL) { goto bail; } } if (PyList_Append(chunks, chunk)) { Py_DECREF(chunk); goto bail; } Py_DECREF(chunk); } rval = join_list_string(chunks); if (rval == NULL) { goto bail; } Py_CLEAR(chunks); *next_end_ptr = end; return rval; bail: *next_end_ptr = -1; Py_XDECREF(chunks); return NULL; } static PyObject * scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict, Py_ssize_t *next_end_ptr) { /* Read the JSON string from PyUnicode pystr. end is the index of the first character after the quote. encoding is the encoding of pystr (must be an ASCII superset) if strict is zero then literal control characters are allowed *next_end_ptr is a return-by-reference index of the character after the end quote Return value is a new PyUnicode */ PyObject *rval; Py_ssize_t len = PyUnicode_GET_SIZE(pystr); Py_ssize_t begin = end - 1; Py_ssize_t next = begin; const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr); PyObject *chunks = PyList_New(0); if (chunks == NULL) { goto bail; } if (end < 0 || len <= end) { PyErr_SetString(PyExc_ValueError, "end is out of bounds"); goto bail; } while (1) { /* Find the end of the string or the next escape */ Py_UNICODE c = 0; PyObject *chunk = NULL; for (next = end; next < len; next++) { c = buf[next]; if (c == '"' || c == '\\') { break; } else if (strict && c <= 0x1f) { raise_errmsg("Invalid control character at", pystr, next); goto bail; } } if (!(c == '"' || c == '\\')) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } /* Pick up this chunk if it's not zero length */ if (next != end) { chunk = PyUnicode_FromUnicode(&buf[end], next - end); if (chunk == NULL) { goto bail; } if (PyList_Append(chunks, chunk)) { Py_DECREF(chunk); goto bail; } Py_DECREF(chunk); } next++; if (c == '"') { end = next; break; } if (next == len) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } c = buf[next]; if (c != 'u') { /* Non-unicode backslash escapes */ end = next + 1; switch (c) { case '"': break; case '\\': break; case '/': break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; default: c = 0; } if (c == 0) { raise_errmsg("Invalid \\escape", pystr, end - 2); goto bail; } } else { c = 0; next++; end = next + 4; if (end >= len) { raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1); goto bail; } /* Decode 4 hex digits */ for (; next < end; next++) { Py_UNICODE digit = buf[next]; c <<= 4; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } #ifdef Py_UNICODE_WIDE /* Surrogate pair */ if ((c & 0xfc00) == 0xd800) { Py_UNICODE c2 = 0; if (end + 6 >= len) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } if (buf[next++] != '\\' || buf[next++] != 'u') { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } end += 6; /* Decode 4 hex digits */ for (; next < end; next++) { c2 <<= 4; Py_UNICODE digit = buf[next]; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c2 |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c2 |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c2 |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } if ((c2 & 0xfc00) != 0xdc00) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00)); } else if ((c & 0xfc00) == 0xdc00) { raise_errmsg("Unpaired low surrogate", pystr, end - 5); goto bail; } #endif } chunk = PyUnicode_FromUnicode(&c, 1); if (chunk == NULL) { goto bail; } if (PyList_Append(chunks, chunk)) { Py_DECREF(chunk); goto bail; } Py_DECREF(chunk); } rval = join_list_unicode(chunks); if (rval == NULL) { goto bail; } Py_DECREF(chunks); *next_end_ptr = end; return rval; bail: *next_end_ptr = -1; Py_XDECREF(chunks); return NULL; } PyDoc_STRVAR(pydoc_scanstring, "scanstring(basestring, end, encoding, strict=True) -> (str, end)\n" "\n" "Scan the string s for a JSON string. End is the index of the\n" "character in s after the quote that started the JSON string.\n" "Unescapes all valid JSON string escape sequences and raises ValueError\n" "on attempt to decode an invalid string. If strict is False then literal\n" "control characters are allowed in the string.\n" "\n" "Returns a tuple of the decoded string and the index of the character in s\n" "after the end quote." ); static PyObject * py_scanstring(PyObject* self UNUSED, PyObject *args) { PyObject *pystr; PyObject *rval; Py_ssize_t end; Py_ssize_t next_end = -1; char *encoding = NULL; int strict = 1; if (!PyArg_ParseTuple(args, "OO&|zi:scanstring", &pystr, _convertPyInt_AsSsize_t, &end, &encoding, &strict)) { return NULL; } if (encoding == NULL) { encoding = DEFAULT_ENCODING; } if (PyString_Check(pystr)) { rval = scanstring_str(pystr, end, encoding, strict, &next_end); } else if (PyUnicode_Check(pystr)) { rval = scanstring_unicode(pystr, end, strict, &next_end); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } return _build_rval_index_tuple(rval, next_end); } PyDoc_STRVAR(pydoc_encode_basestring_ascii, "encode_basestring_ascii(basestring) -> str\n" "\n" "Return an ASCII-only JSON representation of a Python string" ); static PyObject * py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr) { /* Return an ASCII-only JSON representation of a Python string */ /* METH_O */ if (PyString_Check(pystr)) { return ascii_escape_str(pystr); } else if (PyUnicode_Check(pystr)) { return ascii_escape_unicode(pystr); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } } static void scanner_dealloc(PyObject *self) { /* Deallocate scanner object */ PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; Py_CLEAR(s->encoding); Py_CLEAR(s->strict); Py_CLEAR(s->object_hook); Py_CLEAR(s->parse_float); Py_CLEAR(s->parse_int); Py_CLEAR(s->parse_constant); self->ob_type->tp_free(self); } static PyObject * _parse_object_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON object from PyString pystr. idx is the index of the first character after the opening curly brace. *next_idx_ptr is a return-by-reference index to the first character after the closing curly brace. Returns a new PyObject (usually a dict, but object_hook can change that) */ char *str = PyString_AS_STRING(pystr); Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1; PyObject *rval = PyDict_New(); PyObject *key = NULL; PyObject *val = NULL; char *encoding = PyString_AS_STRING(s->encoding); int strict = PyObject_IsTrue(s->strict); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after { */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the object is non-empty */ if (idx <= end_idx && str[idx] != '}') { while (idx <= end_idx) { /* read key */ if (str[idx] != '"') { raise_errmsg("Expecting property name", pystr, idx); goto bail; } key = scanstring_str(pystr, idx + 1, encoding, strict, &next_idx); if (key == NULL) goto bail; idx = next_idx; /* skip whitespace between key and : delimiter, read :, skip whitespace */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; if (idx > end_idx || str[idx] != ':') { raise_errmsg("Expecting : delimiter", pystr, idx); goto bail; } idx++; while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* read any JSON data type */ val = scan_once_str(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyDict_SetItem(rval, key, val) == -1) goto bail; Py_CLEAR(key); Py_CLEAR(val); idx = next_idx; /* skip whitespace before } or , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the object is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == '}') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , delimiter */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be '}' */ if (idx > end_idx || str[idx] != '}') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } /* if object_hook is not None: rval = object_hook(rval) */ if (s->object_hook != Py_None) { val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL); if (val == NULL) goto bail; Py_DECREF(rval); rval = val; val = NULL; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(key); Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_object_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON object from PyUnicode pystr. idx is the index of the first character after the opening curly brace. *next_idx_ptr is a return-by-reference index to the first character after the closing curly brace. Returns a new PyObject (usually a dict, but object_hook can change that) */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; PyObject *val = NULL; PyObject *rval = PyDict_New(); PyObject *key = NULL; int strict = PyObject_IsTrue(s->strict); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after { */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the object is non-empty */ if (idx <= end_idx && str[idx] != '}') { while (idx <= end_idx) { /* read key */ if (str[idx] != '"') { raise_errmsg("Expecting property name", pystr, idx); goto bail; } key = scanstring_unicode(pystr, idx + 1, strict, &next_idx); if (key == NULL) goto bail; idx = next_idx; /* skip whitespace between key and : delimiter, read :, skip whitespace */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; if (idx > end_idx || str[idx] != ':') { raise_errmsg("Expecting : delimiter", pystr, idx); goto bail; } idx++; while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* read any JSON term */ val = scan_once_unicode(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyDict_SetItem(rval, key, val) == -1) goto bail; Py_CLEAR(key); Py_CLEAR(val); idx = next_idx; /* skip whitespace before } or , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the object is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == '}') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , delimiter */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be '}' */ if (idx > end_idx || str[idx] != '}') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } /* if object_hook is not None: rval = object_hook(rval) */ if (s->object_hook != Py_None) { val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL); if (val == NULL) goto bail; Py_DECREF(rval); rval = val; val = NULL; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(key); Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_array_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON array from PyString pystr. idx is the index of the first character after the opening brace. *next_idx_ptr is a return-by-reference index to the first character after the closing brace. Returns a new PyList */ char *str = PyString_AS_STRING(pystr); Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1; PyObject *val = NULL; PyObject *rval = PyList_New(0); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after [ */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the array is non-empty */ if (idx <= end_idx && str[idx] != ']') { while (idx <= end_idx) { /* read any JSON term and de-tuplefy the (rval, idx) */ val = scan_once_str(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyList_Append(rval, val) == -1) goto bail; Py_CLEAR(val); idx = next_idx; /* skip whitespace between term and , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the array is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == ']') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be ']' */ if (idx > end_idx || str[idx] != ']') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_array_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON array from PyString pystr. idx is the index of the first character after the opening brace. *next_idx_ptr is a return-by-reference index to the first character after the closing brace. Returns a new PyList */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; PyObject *val = NULL; PyObject *rval = PyList_New(0); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after [ */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the array is non-empty */ if (idx <= end_idx && str[idx] != ']') { while (idx <= end_idx) { /* read any JSON term */ val = scan_once_unicode(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyList_Append(rval, val) == -1) goto bail; Py_CLEAR(val); idx = next_idx; /* skip whitespace between term and , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the array is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == ']') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be ']' */ if (idx > end_idx || str[idx] != ']') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_constant(PyScannerObject *s, char *constant, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON constant from PyString pystr. constant is the constant string that was found ("NaN", "Infinity", "-Infinity"). idx is the index of the first character of the constant *next_idx_ptr is a return-by-reference index to the first character after the constant. Returns the result of parse_constant */ PyObject *cstr; PyObject *rval; /* constant is "NaN", "Infinity", or "-Infinity" */ cstr = PyString_InternFromString(constant); if (cstr == NULL) return NULL; /* rval = parse_constant(constant) */ rval = PyObject_CallFunctionObjArgs(s->parse_constant, cstr, NULL); idx += PyString_GET_SIZE(cstr); Py_DECREF(cstr); *next_idx_ptr = idx; return rval; } static PyObject * _match_number_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) { /* Read a JSON number from PyString pystr. idx is the index of the first character of the number *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of that number: PyInt, PyLong, or PyFloat. May return other types if parse_int or parse_float are set */ char *str = PyString_AS_STRING(pystr); Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1; Py_ssize_t idx = start; int is_float = 0; PyObject *rval; PyObject *numstr; /* read a sign if it's there, make sure it's not the end of the string */ if (str[idx] == '-') { idx++; if (idx > end_idx) { PyErr_SetNone(PyExc_StopIteration); return NULL; } } /* read as many integer digits as we find as long as it doesn't start with 0 */ if (str[idx] >= '1' && str[idx] <= '9') { idx++; while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if it starts with 0 we only expect one integer digit */ else if (str[idx] == '0') { idx++; } /* no integer digits, error */ else { PyErr_SetNone(PyExc_StopIteration); return NULL; } /* if the next char is '.' followed by a digit then read all float digits */ if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') { is_float = 1; idx += 2; while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */ if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) { /* save the index of the 'e' or 'E' just in case we need to backtrack */ Py_ssize_t e_start = idx; idx++; /* read an exponent sign if present */ if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++; /* read all digits */ while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; /* if we got a digit, then parse as float. if not, backtrack */ if (str[idx - 1] >= '0' && str[idx - 1] <= '9') { is_float = 1; } else { idx = e_start; } } /* copy the section we determined to be a number */ numstr = PyString_FromStringAndSize(&str[start], idx - start); if (numstr == NULL) return NULL; if (is_float) { /* parse as a float using a fast path if available, otherwise call user defined method */ if (s->parse_float != (PyObject *)&PyFloat_Type) { rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL); } else { rval = PyFloat_FromDouble(PyOS_ascii_atof(PyString_AS_STRING(numstr))); } } else { /* parse as an int using a fast path if available, otherwise call user defined method */ if (s->parse_int != (PyObject *)&PyInt_Type) { rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL); } else { rval = PyInt_FromString(PyString_AS_STRING(numstr), NULL, 10); } } Py_DECREF(numstr); *next_idx_ptr = idx; return rval; } static PyObject * _match_number_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) { /* Read a JSON number from PyUnicode pystr. idx is the index of the first character of the number *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of that number: PyInt, PyLong, or PyFloat. May return other types if parse_int or parse_float are set */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; Py_ssize_t idx = start; int is_float = 0; PyObject *rval; PyObject *numstr; /* read a sign if it's there, make sure it's not the end of the string */ if (str[idx] == '-') { idx++; if (idx > end_idx) { PyErr_SetNone(PyExc_StopIteration); return NULL; } } /* read as many integer digits as we find as long as it doesn't start with 0 */ if (str[idx] >= '1' && str[idx] <= '9') { idx++; while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if it starts with 0 we only expect one integer digit */ else if (str[idx] == '0') { idx++; } /* no integer digits, error */ else { PyErr_SetNone(PyExc_StopIteration); return NULL; } /* if the next char is '.' followed by a digit then read all float digits */ if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') { is_float = 1; idx += 2; while (idx < end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */ if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) { Py_ssize_t e_start = idx; idx++; /* read an exponent sign if present */ if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++; /* read all digits */ while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; /* if we got a digit, then parse as float. if not, backtrack */ if (str[idx - 1] >= '0' && str[idx - 1] <= '9') { is_float = 1; } else { idx = e_start; } } /* copy the section we determined to be a number */ numstr = PyUnicode_FromUnicode(&str[start], idx - start); if (numstr == NULL) return NULL; if (is_float) { /* parse as a float using a fast path if available, otherwise call user defined method */ if (s->parse_float != (PyObject *)&PyFloat_Type) { rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL); } else { rval = PyFloat_FromString(numstr, NULL); } } else { /* no fast path for unicode -> int, just call */ rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL); } Py_DECREF(numstr); *next_idx_ptr = idx; return rval; } static PyObject * scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read one JSON term (of any kind) from PyString pystr. idx is the index of the first character of the term *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of the term. */ char *str = PyString_AS_STRING(pystr); Py_ssize_t length = PyString_GET_SIZE(pystr); if (idx >= length) { PyErr_SetNone(PyExc_StopIteration); return NULL; } switch (str[idx]) { case '"': /* string */ return scanstring_str(pystr, idx + 1, PyString_AS_STRING(s->encoding), PyObject_IsTrue(s->strict), next_idx_ptr); case '{': /* object */ return _parse_object_str(s, pystr, idx + 1, next_idx_ptr); case '[': /* array */ return _parse_array_str(s, pystr, idx + 1, next_idx_ptr); case 'n': /* null */ if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') { Py_INCREF(Py_None); *next_idx_ptr = idx + 4; return Py_None; } break; case 't': /* true */ if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') { Py_INCREF(Py_True); *next_idx_ptr = idx + 4; return Py_True; } break; case 'f': /* false */ if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') { Py_INCREF(Py_False); *next_idx_ptr = idx + 5; return Py_False; } break; case 'N': /* NaN */ if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') { return _parse_constant(s, "NaN", idx, next_idx_ptr); } break; case 'I': /* Infinity */ if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') { return _parse_constant(s, "Infinity", idx, next_idx_ptr); } break; case '-': /* -Infinity */ if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') { return _parse_constant(s, "-Infinity", idx, next_idx_ptr); } break; } /* Didn't find a string, object, array, or named constant. Look for a number. */ return _match_number_str(s, pystr, idx, next_idx_ptr); } static PyObject * scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read one JSON term (of any kind) from PyUnicode pystr. idx is the index of the first character of the term *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of the term. */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t length = PyUnicode_GET_SIZE(pystr); if (idx >= length) { PyErr_SetNone(PyExc_StopIteration); return NULL; } switch (str[idx]) { case '"': /* string */ return scanstring_unicode(pystr, idx + 1, PyObject_IsTrue(s->strict), next_idx_ptr); case '{': /* object */ return _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr); case '[': /* array */ return _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr); case 'n': /* null */ if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') { Py_INCREF(Py_None); *next_idx_ptr = idx + 4; return Py_None; } break; case 't': /* true */ if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') { Py_INCREF(Py_True); *next_idx_ptr = idx + 4; return Py_True; } break; case 'f': /* false */ if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') { Py_INCREF(Py_False); *next_idx_ptr = idx + 5; return Py_False; } break; case 'N': /* NaN */ if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') { return _parse_constant(s, "NaN", idx, next_idx_ptr); } break; case 'I': /* Infinity */ if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') { return _parse_constant(s, "Infinity", idx, next_idx_ptr); } break; case '-': /* -Infinity */ if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') { return _parse_constant(s, "-Infinity", idx, next_idx_ptr); } break; } /* Didn't find a string, object, array, or named constant. Look for a number. */ return _match_number_unicode(s, pystr, idx, next_idx_ptr); } static PyObject * scanner_call(PyObject *self, PyObject *args, PyObject *kwds) { /* Python callable interface to scan_once_{str,unicode} */ PyObject *pystr; PyObject *rval; Py_ssize_t idx; Py_ssize_t next_idx = -1; static char *kwlist[] = {"string", "idx", NULL}; PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:scan_once", kwlist, &pystr, _convertPyInt_AsSsize_t, &idx)) return NULL; if (PyString_Check(pystr)) { rval = scan_once_str(s, pystr, idx, &next_idx); } else if (PyUnicode_Check(pystr)) { rval = scan_once_unicode(s, pystr, idx, &next_idx); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } return _build_rval_index_tuple(rval, next_idx); } static int scanner_init(PyObject *self, PyObject *args, PyObject *kwds) { /* Initialize Scanner object */ PyObject *ctx; static char *kwlist[] = {"context", NULL}; PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:make_scanner", kwlist, &ctx)) return -1; s->encoding = NULL; s->strict = NULL; s->object_hook = NULL; s->parse_float = NULL; s->parse_int = NULL; s->parse_constant = NULL; /* PyString_AS_STRING is used on encoding */ s->encoding = PyObject_GetAttrString(ctx, "encoding"); if (s->encoding == Py_None) { Py_DECREF(Py_None); s->encoding = PyString_InternFromString(DEFAULT_ENCODING); } else if (PyUnicode_Check(s->encoding)) { PyObject *tmp = PyUnicode_AsEncodedString(s->encoding, NULL, NULL); Py_DECREF(s->encoding); s->encoding = tmp; } if (s->encoding == NULL || !PyString_Check(s->encoding)) goto bail; /* All of these will fail "gracefully" so we don't need to verify them */ s->strict = PyObject_GetAttrString(ctx, "strict"); if (s->strict == NULL) goto bail; s->object_hook = PyObject_GetAttrString(ctx, "object_hook"); if (s->object_hook == NULL) goto bail; s->parse_float = PyObject_GetAttrString(ctx, "parse_float"); if (s->parse_float == NULL) goto bail; s->parse_int = PyObject_GetAttrString(ctx, "parse_int"); if (s->parse_int == NULL) goto bail; s->parse_constant = PyObject_GetAttrString(ctx, "parse_constant"); if (s->parse_constant == NULL) goto bail; return 0; bail: Py_CLEAR(s->encoding); Py_CLEAR(s->strict); Py_CLEAR(s->object_hook); Py_CLEAR(s->parse_float); Py_CLEAR(s->parse_int); Py_CLEAR(s->parse_constant); return -1; } PyDoc_STRVAR(scanner_doc, "JSON scanner object"); static PyTypeObject PyScannerType = { PyObject_HEAD_INIT(0) 0, /* tp_internal */ "Scanner", /* tp_name */ sizeof(PyScannerObject), /* tp_basicsize */ 0, /* tp_itemsize */ scanner_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ scanner_call, /* tp_call */ 0, /* tp_str */ 0,/* PyObject_GenericGetAttr, */ /* tp_getattro */ 0,/* PyObject_GenericSetAttr, */ /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ scanner_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ scanner_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ scanner_init, /* tp_init */ 0,/* PyType_GenericAlloc, */ /* tp_alloc */ 0,/* PyType_GenericNew, */ /* tp_new */ 0,/* _PyObject_Del, */ /* tp_free */ }; static int encoder_init(PyObject *self, PyObject *args, PyObject *kwds) { /* initialize Encoder object */ static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", NULL}; PyEncoderObject *s; PyObject *allow_nan; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; s->markers = NULL; s->defaultfn = NULL; s->encoder = NULL; s->indent = NULL; s->key_separator = NULL; s->item_separator = NULL; s->sort_keys = NULL; s->skipkeys = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOO:make_encoder", kwlist, &s->markers, &s->defaultfn, &s->encoder, &s->indent, &s->key_separator, &s->item_separator, &s->sort_keys, &s->skipkeys, &allow_nan)) return -1; Py_INCREF(s->markers); Py_INCREF(s->defaultfn); Py_INCREF(s->encoder); Py_INCREF(s->indent); Py_INCREF(s->key_separator); Py_INCREF(s->item_separator); Py_INCREF(s->sort_keys); Py_INCREF(s->skipkeys); s->fast_encode = (PyCFunction_Check(s->encoder) && PyCFunction_GetFunction(s->encoder) == (PyCFunction)py_encode_basestring_ascii); s->allow_nan = PyObject_IsTrue(allow_nan); return 0; } static PyObject * encoder_call(PyObject *self, PyObject *args, PyObject *kwds) { /* Python callable interface to encode_listencode_obj */ static char *kwlist[] = {"obj", "_current_indent_level", NULL}; PyObject *obj; PyObject *rval; Py_ssize_t indent_level; PyEncoderObject *s; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:_iterencode", kwlist, &obj, _convertPyInt_AsSsize_t, &indent_level)) return NULL; rval = PyList_New(0); if (rval == NULL) return NULL; if (encoder_listencode_obj(s, rval, obj, indent_level)) { Py_DECREF(rval); return NULL; } return rval; } static PyObject * _encoded_const(PyObject *obj) { /* Return the JSON string representation of None, True, False */ if (obj == Py_None) { static PyObject *s_null = NULL; if (s_null == NULL) { s_null = PyString_InternFromString("null"); } Py_INCREF(s_null); return s_null; } else if (obj == Py_True) { static PyObject *s_true = NULL; if (s_true == NULL) { s_true = PyString_InternFromString("true"); } Py_INCREF(s_true); return s_true; } else if (obj == Py_False) { static PyObject *s_false = NULL; if (s_false == NULL) { s_false = PyString_InternFromString("false"); } Py_INCREF(s_false); return s_false; } else { PyErr_SetString(PyExc_ValueError, "not a const"); return NULL; } } static PyObject * encoder_encode_float(PyEncoderObject *s, PyObject *obj) { /* Return the JSON representation of a PyFloat */ double i = PyFloat_AS_DOUBLE(obj); if (!Py_IS_FINITE(i)) { if (!s->allow_nan) { PyErr_SetString(PyExc_ValueError, "Out of range float values are not JSON compliant"); return NULL; } if (i > 0) { return PyString_FromString("Infinity"); } else if (i < 0) { return PyString_FromString("-Infinity"); } else { return PyString_FromString("NaN"); } } /* Use a better float format here? */ return PyObject_Repr(obj); } static PyObject * encoder_encode_string(PyEncoderObject *s, PyObject *obj) { /* Return the JSON representation of a string */ if (s->fast_encode) return py_encode_basestring_ascii(NULL, obj); else return PyObject_CallFunctionObjArgs(s->encoder, obj, NULL); } static int _steal_list_append(PyObject *lst, PyObject *stolen) { /* Append stolen and then decrement its reference count */ int rval = PyList_Append(lst, stolen); Py_DECREF(stolen); return rval; } static int encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level) { /* Encode Python object obj to a JSON term, rval is a PyList */ PyObject *newobj; int rv; if (obj == Py_None || obj == Py_True || obj == Py_False) { PyObject *cstr = _encoded_const(obj); if (cstr == NULL) return -1; return _steal_list_append(rval, cstr); } else if (PyString_Check(obj) || PyUnicode_Check(obj)) { PyObject *encoded = encoder_encode_string(s, obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyInt_Check(obj) || PyLong_Check(obj)) { PyObject *encoded = PyObject_Str(obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyFloat_Check(obj)) { PyObject *encoded = encoder_encode_float(s, obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyList_Check(obj) || PyTuple_Check(obj)) { return encoder_listencode_list(s, rval, obj, indent_level); } else if (PyDict_Check(obj)) { return encoder_listencode_dict(s, rval, obj, indent_level); } else { PyObject *ident = NULL; if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(obj); if (ident == NULL) return -1; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); Py_DECREF(ident); return -1; } if (PyDict_SetItem(s->markers, ident, obj)) { Py_DECREF(ident); return -1; } } newobj = PyObject_CallFunctionObjArgs(s->defaultfn, obj, NULL); if (newobj == NULL) { Py_XDECREF(ident); return -1; } rv = encoder_listencode_obj(s, rval, newobj, indent_level); Py_DECREF(newobj); if (rv) { Py_XDECREF(ident); return -1; } if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) { Py_XDECREF(ident); return -1; } Py_XDECREF(ident); } return rv; } } static int encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level) { /* Encode Python dict dct a JSON term, rval is a PyList */ static PyObject *open_dict = NULL; static PyObject *close_dict = NULL; static PyObject *empty_dict = NULL; PyObject *kstr = NULL; PyObject *ident = NULL; PyObject *key, *value; Py_ssize_t pos; int skipkeys; Py_ssize_t idx; if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) { open_dict = PyString_InternFromString("{"); close_dict = PyString_InternFromString("}"); empty_dict = PyString_InternFromString("{}"); if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) return -1; } if (PyDict_Size(dct) == 0) return PyList_Append(rval, empty_dict); if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(dct); if (ident == NULL) goto bail; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); goto bail; } if (PyDict_SetItem(s->markers, ident, dct)) { goto bail; } } if (PyList_Append(rval, open_dict)) goto bail; if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level += 1; /* newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent */ } /* TODO: C speedup not implemented for sort_keys */ pos = 0; skipkeys = PyObject_IsTrue(s->skipkeys); idx = 0; while (PyDict_Next(dct, &pos, &key, &value)) { PyObject *encoded; if (PyString_Check(key) || PyUnicode_Check(key)) { Py_INCREF(key); kstr = key; } else if (PyFloat_Check(key)) { kstr = encoder_encode_float(s, key); if (kstr == NULL) goto bail; } else if (PyInt_Check(key) || PyLong_Check(key)) { kstr = PyObject_Str(key); if (kstr == NULL) goto bail; } else if (key == Py_True || key == Py_False || key == Py_None) { kstr = _encoded_const(key); if (kstr == NULL) goto bail; } else if (skipkeys) { continue; } else { /* TODO: include repr of key */ PyErr_SetString(PyExc_ValueError, "keys must be a string"); goto bail; } if (idx) { if (PyList_Append(rval, s->item_separator)) goto bail; } encoded = encoder_encode_string(s, kstr); Py_CLEAR(kstr); if (encoded == NULL) goto bail; if (PyList_Append(rval, encoded)) { Py_DECREF(encoded); goto bail; } Py_DECREF(encoded); if (PyList_Append(rval, s->key_separator)) goto bail; if (encoder_listencode_obj(s, rval, value, indent_level)) goto bail; idx += 1; } if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) goto bail; Py_CLEAR(ident); } if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level -= 1; /* yield '\n' + (' ' * (_indent * _current_indent_level)) */ } if (PyList_Append(rval, close_dict)) goto bail; return 0; bail: Py_XDECREF(kstr); Py_XDECREF(ident); return -1; } static int encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level) { /* Encode Python list seq to a JSON term, rval is a PyList */ static PyObject *open_array = NULL; static PyObject *close_array = NULL; static PyObject *empty_array = NULL; PyObject *ident = NULL; PyObject *s_fast = NULL; Py_ssize_t num_items; PyObject **seq_items; Py_ssize_t i; if (open_array == NULL || close_array == NULL || empty_array == NULL) { open_array = PyString_InternFromString("["); close_array = PyString_InternFromString("]"); empty_array = PyString_InternFromString("[]"); if (open_array == NULL || close_array == NULL || empty_array == NULL) return -1; } ident = NULL; s_fast = PySequence_Fast(seq, "_iterencode_list needs a sequence"); if (s_fast == NULL) return -1; num_items = PySequence_Fast_GET_SIZE(s_fast); if (num_items == 0) { Py_DECREF(s_fast); return PyList_Append(rval, empty_array); } if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(seq); if (ident == NULL) goto bail; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); goto bail; } if (PyDict_SetItem(s->markers, ident, seq)) { goto bail; } } seq_items = PySequence_Fast_ITEMS(s_fast); if (PyList_Append(rval, open_array)) goto bail; if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level += 1; /* newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent */ } for (i = 0; i < num_items; i++) { PyObject *obj = seq_items[i]; if (i) { if (PyList_Append(rval, s->item_separator)) goto bail; } if (encoder_listencode_obj(s, rval, obj, indent_level)) goto bail; } if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) goto bail; Py_CLEAR(ident); } if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level -= 1; /* yield '\n' + (' ' * (_indent * _current_indent_level)) */ } if (PyList_Append(rval, close_array)) goto bail; Py_DECREF(s_fast); return 0; bail: Py_XDECREF(ident); Py_DECREF(s_fast); return -1; } static void encoder_dealloc(PyObject *self) { /* Deallocate Encoder */ PyEncoderObject *s; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; Py_CLEAR(s->markers); Py_CLEAR(s->defaultfn); Py_CLEAR(s->encoder); Py_CLEAR(s->indent); Py_CLEAR(s->key_separator); Py_CLEAR(s->item_separator); Py_CLEAR(s->sort_keys); Py_CLEAR(s->skipkeys); self->ob_type->tp_free(self); } PyDoc_STRVAR(encoder_doc, "_iterencode(obj, _current_indent_level) -> iterable"); static PyTypeObject PyEncoderType = { PyObject_HEAD_INIT(0) 0, /* tp_internal */ "Encoder", /* tp_name */ sizeof(PyEncoderObject), /* tp_basicsize */ 0, /* tp_itemsize */ encoder_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ encoder_call, /* tp_call */ 0, /* tp_str */ 0,/* PyObject_GenericGetAttr, */ /* tp_getattro */ 0,/* PyObject_GenericSetAttr, */ /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ encoder_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ encoder_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ encoder_init, /* tp_init */ 0,/* PyType_GenericAlloc, */ /* tp_alloc */ 0,/* PyType_GenericNew, */ /* tp_new */ 0,/* _PyObject_Del, */ /* tp_free */ }; static PyMethodDef speedups_methods[] = { {"encode_basestring_ascii", (PyCFunction)py_encode_basestring_ascii, METH_O, pydoc_encode_basestring_ascii}, {"scanstring", (PyCFunction)py_scanstring, METH_VARARGS, pydoc_scanstring}, {NULL, NULL, 0, NULL} }; PyDoc_STRVAR(module_doc, "simplejson speedups\n"); void init_speedups(void) { PyObject *m; PyScannerType.tp_getattro = PyObject_GenericGetAttr; PyScannerType.tp_setattro = PyObject_GenericSetAttr; PyScannerType.tp_alloc = PyType_GenericAlloc; PyScannerType.tp_new = PyType_GenericNew; PyScannerType.tp_free = _PyObject_Del; if (PyType_Ready(&PyScannerType) < 0) return; PyEncoderType.tp_getattro = PyObject_GenericGetAttr; PyEncoderType.tp_setattro = PyObject_GenericSetAttr; PyEncoderType.tp_alloc = PyType_GenericAlloc; PyEncoderType.tp_new = PyType_GenericNew; PyEncoderType.tp_free = _PyObject_Del; if (PyType_Ready(&PyEncoderType) < 0) return; m = Py_InitModule3("_speedups", speedups_methods, module_doc); Py_INCREF((PyObject*)&PyScannerType); PyModule_AddObject(m, "make_scanner", (PyObject*)&PyScannerType); Py_INCREF((PyObject*)&PyEncoderType); PyModule_AddObject(m, "make_encoder", (PyObject*)&PyEncoderType); }
123danielbenjaminphilpott-123
simplejson/_speedups.c
C
asf20
75,169
"""Implementation of JSONDecoder """ import re import sys import struct from simplejson.scanner import make_scanner try: from simplejson._speedups import scanstring as c_scanstring except ImportError: c_scanstring = None __all__ = ['JSONDecoder'] FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL def _floatconstants(): _BYTES = '7FF80000000000007FF0000000000000'.decode('hex') if sys.byteorder != 'big': _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1] nan, inf = struct.unpack('dd', _BYTES) return nan, inf, -inf NaN, PosInf, NegInf = _floatconstants() def linecol(doc, pos): lineno = doc.count('\n', 0, pos) + 1 if lineno == 1: colno = pos else: colno = pos - doc.rindex('\n', 0, pos) return lineno, colno def errmsg(msg, doc, pos, end=None): # Note that this function is called from _speedups lineno, colno = linecol(doc, pos) if end is None: return '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos) endlineno, endcolno = linecol(doc, end) return '%s: line %d column %d - line %d column %d (char %d - %d)' % ( msg, lineno, colno, endlineno, endcolno, pos, end) _CONSTANTS = { '-Infinity': NegInf, 'Infinity': PosInf, 'NaN': NaN, } STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS) BACKSLASH = { '"': u'"', '\\': u'\\', '/': u'/', 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t', } DEFAULT_ENCODING = "utf-8" def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match): """Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string. If strict is False then literal control characters are allowed in the string. Returns a tuple of the decoded string and the index of the character in s after the end quote.""" if encoding is None: encoding = DEFAULT_ENCODING chunks = [] _append = chunks.append begin = end - 1 while 1: chunk = _m(s, end) if chunk is None: raise ValueError( errmsg("Unterminated string starting at", s, begin)) end = chunk.end() content, terminator = chunk.groups() # Content is contains zero or more unescaped string characters if content: if not isinstance(content, unicode): content = unicode(content, encoding) _append(content) # Terminator is the end of string, a literal control character, # or a backslash denoting that an escape sequence follows if terminator == '"': break elif terminator != '\\': if strict: msg = "Invalid control character %r at" % (terminator,) raise ValueError(msg, s, end) else: _append(terminator) continue try: esc = s[end] except IndexError: raise ValueError( errmsg("Unterminated string starting at", s, begin)) # If not a unicode escape sequence, must be in the lookup table if esc != 'u': try: char = _b[esc] except KeyError: raise ValueError( errmsg("Invalid \\escape: %r" % (esc,), s, end)) end += 1 else: # Unicode escape sequence esc = s[end + 1:end + 5] next_end = end + 5 if len(esc) != 4: msg = "Invalid \\uXXXX escape" raise ValueError(errmsg(msg, s, end)) uni = int(esc, 16) # Check for surrogate pair on UCS-4 systems if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535: msg = "Invalid \\uXXXX\\uXXXX surrogate pair" if not s[end + 5:end + 7] == '\\u': raise ValueError(errmsg(msg, s, end)) esc2 = s[end + 7:end + 11] if len(esc2) != 4: raise ValueError(errmsg(msg, s, end)) uni2 = int(esc2, 16) uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) next_end += 6 char = unichr(uni) end = next_end # Append the unescaped character _append(char) return u''.join(chunks), end # Use speedup if available scanstring = c_scanstring or py_scanstring WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS) WHITESPACE_STR = ' \t\n\r' def JSONObject((s, end), encoding, strict, scan_once, object_hook, _w=WHITESPACE.match, _ws=WHITESPACE_STR): pairs = {} # Use a slice to prevent IndexError from being raised, the following # check will raise a more specific ValueError if the string is empty nextchar = s[end:end + 1] # Normally we expect nextchar == '"' if nextchar != '"': if nextchar in _ws: end = _w(s, end).end() nextchar = s[end:end + 1] # Trivial empty object if nextchar == '}': return pairs, end + 1 elif nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end)) end += 1 while True: key, end = scanstring(s, end, encoding, strict) # To skip some function call overhead we optimize the fast paths where # the JSON key separator is ": " or just ":". if s[end:end + 1] != ':': end = _w(s, end).end() if s[end:end + 1] != ':': raise ValueError(errmsg("Expecting : delimiter", s, end)) end += 1 try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass try: value, end = scan_once(s, end) except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) pairs[key] = value try: nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar == '}': break elif nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end - 1)) try: nextchar = s[end] if nextchar in _ws: end += 1 nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end - 1)) if object_hook is not None: pairs = object_hook(pairs) return pairs, end def JSONArray((s, end), scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR): values = [] nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] # Look-ahead for trivial empty array if nextchar == ']': return values, end + 1 _append = values.append while True: try: value, end = scan_once(s, end) except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) _append(value) nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] end += 1 if nextchar == ']': break elif nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end)) try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass return values, end class JSONDecoder(object): """Simple JSON <http://json.org> decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | unicode | +---------------+-------------------+ | number (int) | int, long | +---------------+-------------------+ | number (real) | float | +---------------+-------------------+ | true | True | +---------------+-------------------+ | false | False | +---------------+-------------------+ | null | None | +---------------+-------------------+ It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their corresponding ``float`` values, which is outside the JSON spec. """ def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True): """``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no effect when decoding ``unicode`` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as ``unicode``. ``object_hook``, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given ``dict``. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered. """ self.encoding = encoding self.object_hook = object_hook self.parse_float = parse_float or float self.parse_int = parse_int or int self.parse_constant = parse_constant or _CONSTANTS.__getitem__ self.strict = strict self.parse_object = JSONObject self.parse_array = JSONArray self.parse_string = scanstring self.scan_once = make_scanner(self) def decode(self, s, _w=WHITESPACE.match): """Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) """ obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise ValueError(errmsg("Extra data", s, end, len(s))) return obj def raw_decode(self, s, idx=0): """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end. """ try: obj, end = self.scan_once(s, idx) except StopIteration: raise ValueError("No JSON object could be decoded") return obj, end
123danielbenjaminphilpott-123
simplejson/decoder.py
Python
asf20
12,032
"""JSON token scanner """ import re try: from simplejson._speedups import make_scanner as c_make_scanner except ImportError: c_make_scanner = None __all__ = ['make_scanner'] NUMBER_RE = re.compile( r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?', (re.VERBOSE | re.MULTILINE | re.DOTALL)) def py_make_scanner(context): parse_object = context.parse_object parse_array = context.parse_array parse_string = context.parse_string match_number = NUMBER_RE.match encoding = context.encoding strict = context.strict parse_float = context.parse_float parse_int = context.parse_int parse_constant = context.parse_constant object_hook = context.object_hook def _scan_once(string, idx): try: nextchar = string[idx] except IndexError: raise StopIteration if nextchar == '"': return parse_string(string, idx + 1, encoding, strict) elif nextchar == '{': return parse_object((string, idx + 1), encoding, strict, _scan_once, object_hook) elif nextchar == '[': return parse_array((string, idx + 1), _scan_once) elif nextchar == 'n' and string[idx:idx + 4] == 'null': return None, idx + 4 elif nextchar == 't' and string[idx:idx + 4] == 'true': return True, idx + 4 elif nextchar == 'f' and string[idx:idx + 5] == 'false': return False, idx + 5 m = match_number(string, idx) if m is not None: integer, frac, exp = m.groups() if frac or exp: res = parse_float(integer + (frac or '') + (exp or '')) else: res = parse_int(integer) return res, m.end() elif nextchar == 'N' and string[idx:idx + 3] == 'NaN': return parse_constant('NaN'), idx + 3 elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity': return parse_constant('Infinity'), idx + 8 elif nextchar == '-' and string[idx:idx + 9] == '-Infinity': return parse_constant('-Infinity'), idx + 9 else: raise StopIteration return _scan_once make_scanner = c_make_scanner or py_make_scanner
123danielbenjaminphilpott-123
simplejson/scanner.py
Python
asf20
2,227
"""Implementation of JSONEncoder """ import re try: from simplejson._speedups import encode_basestring_ascii as c_encode_basestring_ascii except ImportError: c_encode_basestring_ascii = None try: from simplejson._speedups import make_encoder as c_make_encoder except ImportError: c_make_encoder = None ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') HAS_UTF8 = re.compile(r'[\x80-\xff]') ESCAPE_DCT = { '\\': '\\\\', '"': '\\"', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', } for i in range(0x20): ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) # Assume this produces an infinity on all machines (probably not guaranteed) INFINITY = float('1e66666') FLOAT_REPR = repr def encode_basestring(s): """Return a JSON representation of a Python string """ def replace(match): return ESCAPE_DCT[match.group(0)] return '"' + ESCAPE.sub(replace, s) + '"' def py_encode_basestring_ascii(s): """Return an ASCII-only JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): s = match.group(0) try: return ESCAPE_DCT[s] except KeyError: n = ord(s) if n < 0x10000: return '\\u%04x' % (n,) else: # surrogate pair n -= 0x10000 s1 = 0xd800 | ((n >> 10) & 0x3ff) s2 = 0xdc00 | (n & 0x3ff) return '\\u%04x\\u%04x' % (s1, s2) return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' encode_basestring_ascii = c_encode_basestring_ascii or py_encode_basestring_ascii class JSONEncoder(object): """Extensible JSON <http://json.org> encoder for Python data structures. Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str, unicode | string | +-------------------+---------------+ | int, long, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ To extend this to recognize other objects, subclass and implement a ``.default()`` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise ``TypeError``). """ item_separator = ', ' key_separator = ': ' def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None): """Constructor for JSONEncoder, with sensible defaults. If skipkeys is False, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is True, the output is guaranteed to be str objects with all incoming unicode characters escaped. If ensure_ascii is false, the output will be unicode object. If check_circular is True, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is True, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is True, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation. If specified, separators should be a (item_separator, key_separator) tuple. The default is (', ', ': '). To get the most compact JSON representation you should specify (',', ':') to eliminate whitespace. If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a ``TypeError``. If encoding is not None, then all input strings will be transformed into unicode using that encoding prior to JSON-encoding. The default is UTF-8. """ self.skipkeys = skipkeys self.ensure_ascii = ensure_ascii self.check_circular = check_circular self.allow_nan = allow_nan self.sort_keys = sort_keys self.indent = indent if separators is not None: self.item_separator, self.key_separator = separators if default is not None: self.default = default self.encoding = encoding def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o) """ raise TypeError("%r is not JSON serializable" % (o,)) def encode(self, o): """Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}' """ # This is for extremely simple cases and benchmarks. if isinstance(o, basestring): if isinstance(o, str): _encoding = self.encoding if (_encoding is not None and not (_encoding == 'utf-8')): o = o.decode(_encoding) if self.ensure_ascii: return encode_basestring_ascii(o) else: return encode_basestring(o) # This doesn't pass the iterator directly to ''.join() because the # exceptions aren't as detailed. The list call should be roughly # equivalent to the PySequence_Fast that ''.join() would do. chunks = self.iterencode(o, _one_shot=True) if not isinstance(chunks, (list, tuple)): chunks = list(chunks) return ''.join(chunks) def iterencode(self, o, _one_shot=False): """Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encode_basestring_ascii else: _encoder = encode_basestring if self.encoding != 'utf-8': def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): if isinstance(o, str): o = o.decode(_encoding) return _orig_encoder(o) def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY): # Check for specials. Note that this type of test is processor- and/or # platform-specific, so do tests which don't depend on the internals. if o != o: text = 'NaN' elif o == _inf: text = 'Infinity' elif o == _neginf: text = '-Infinity' else: return _repr(o) if not allow_nan: raise ValueError("Out of range float values are not JSON compliant: %r" % (o,)) return text if _one_shot and c_make_encoder is not None and not self.indent and not self.sort_keys: _iterencode = c_make_encoder( markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan) else: _iterencode = _make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot) return _iterencode(o, 0) def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, ## HACK: hand-optimized bytecode; turn globals into locals False=False, True=True, ValueError=ValueError, basestring=basestring, dict=dict, float=float, id=id, int=int, isinstance=isinstance, list=list, long=long, str=str, tuple=tuple, ): def _iterencode_list(lst, _current_indent_level): if not lst: yield '[]' return if markers is not None: markerid = id(lst) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = lst buf = '[' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent else: newline_indent = None separator = _item_separator first = True for value in lst: if first: first = False else: buf = separator if isinstance(value, basestring): yield buf + _encoder(value) elif value is None: yield buf + 'null' elif value is True: yield buf + 'true' elif value is False: yield buf + 'false' elif isinstance(value, (int, long)): yield buf + str(value) elif isinstance(value, float): yield buf + _floatstr(value) else: yield buf if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (' ' * (_indent * _current_indent_level)) yield ']' if markers is not None: del markers[markerid] def _iterencode_dict(dct, _current_indent_level): if not dct: yield '{}' return if markers is not None: markerid = id(dct) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = dct yield '{' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) item_separator = _item_separator + newline_indent yield newline_indent else: newline_indent = None item_separator = _item_separator first = True if _sort_keys: items = dct.items() items.sort(key=lambda kv: kv[0]) else: items = dct.iteritems() for key, value in items: if isinstance(key, basestring): pass # JavaScript is weakly typed for these, so it makes sense to # also allow them. Many encoders seem to do something like this. elif isinstance(key, float): key = _floatstr(key) elif isinstance(key, (int, long)): key = str(key) elif key is True: key = 'true' elif key is False: key = 'false' elif key is None: key = 'null' elif _skipkeys: continue else: raise TypeError("key %r is not a string" % (key,)) if first: first = False else: yield item_separator yield _encoder(key) yield _key_separator if isinstance(value, basestring): yield _encoder(value) elif value is None: yield 'null' elif value is True: yield 'true' elif value is False: yield 'false' elif isinstance(value, (int, long)): yield str(value) elif isinstance(value, float): yield _floatstr(value) else: if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (' ' * (_indent * _current_indent_level)) yield '}' if markers is not None: del markers[markerid] def _iterencode(o, _current_indent_level): if isinstance(o, basestring): yield _encoder(o) elif o is None: yield 'null' elif o is True: yield 'true' elif o is False: yield 'false' elif isinstance(o, (int, long)): yield str(o) elif isinstance(o, float): yield _floatstr(o) elif isinstance(o, (list, tuple)): for chunk in _iterencode_list(o, _current_indent_level): yield chunk elif isinstance(o, dict): for chunk in _iterencode_dict(o, _current_indent_level): yield chunk else: if markers is not None: markerid = id(o) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = o o = _default(o) for chunk in _iterencode(o, _current_indent_level): yield chunk if markers is not None: del markers[markerid] return _iterencode
123danielbenjaminphilpott-123
simplejson/encoder.py
Python
asf20
15,836
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. :mod:`simplejson` exposes an API familiar to users of the standard library :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained version of the :mod:`json` library contained in Python 2.6, but maintains compatibility with Python 2.4 and Python 2.5 and (currently) has significant performance advantages, even without using the optional C extension for speedups. Encoding basic Python object hierarchies:: >>> import simplejson as json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print json.dumps("\"foo\bar") "\"foo\bar" >>> print json.dumps(u'\u1234') "\u1234" >>> print json.dumps('\\') "\\" >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) {"a": 0, "b": 0, "c": 0} >>> from StringIO import StringIO >>> io = StringIO() >>> json.dump(['streaming API'], io) >>> io.getvalue() '["streaming API"]' Compact encoding:: >>> import simplejson as json >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) '[1,2,3,{"4":5,"6":7}]' Pretty printing:: >>> import simplejson as json >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) >>> print '\n'.join([l.rstrip() for l in s.splitlines()]) { "4": 5, "6": 7 } Decoding JSON:: >>> import simplejson as json >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj True >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar' True >>> from StringIO import StringIO >>> io = StringIO('["streaming API"]') >>> json.load(io)[0] == 'streaming API' True Specializing JSON object decoding:: >>> import simplejson as json >>> def as_complex(dct): ... if '__complex__' in dct: ... return complex(dct['real'], dct['imag']) ... return dct ... >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', ... object_hook=as_complex) (1+2j) >>> import decimal >>> json.loads('1.1', parse_float=decimal.Decimal) == decimal.Decimal('1.1') True Specializing JSON object encoding:: >>> import simplejson as json >>> def encode_complex(obj): ... if isinstance(obj, complex): ... return [obj.real, obj.imag] ... raise TypeError("%r is not JSON serializable" % (o,)) ... >>> json.dumps(2 + 1j, default=encode_complex) '[2.0, 1.0]' >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j) '[2.0, 1.0]' >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j)) '[2.0, 1.0]' Using simplejson.tool from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -msimplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -msimplejson.tool Expecting property name: line 1 column 2 (char 2) """ __version__ = '2.0.7' __all__ = [ 'dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONEncoder', ] from decoder import JSONDecoder from encoder import JSONEncoder _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, ) def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp`` may be ``unicode`` instances, subject to normal Python ``str`` to ``unicode`` coercion rules. Unless ``fp.write()`` explicitly understands ``unicode`` (as in ``codecs.getwriter()``) this is likely to cause an error. If ``check_circular`` is ``False``, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (skipkeys is False and ensure_ascii is True and check_circular is True and allow_nan is True and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not kw): iterable = _default_encoder.iterencode(obj) else: if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost for chunk in iterable: fp.write(chunk) def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is ``False``, then the return value will be a ``unicode`` instance subject to normal Python ``str`` to ``unicode`` coercion rules instead of being escaped to an ASCII ``str``. If ``check_circular`` is ``False``, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (skipkeys is False and ensure_ascii is True and check_circular is True and allow_nan is True and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not kw): return _default_encoder.encode(obj) if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, **kw).encode(obj) _default_decoder = JSONDecoder(encoding=None, object_hook=None) def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw): """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. If the contents of ``fp`` is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed, and should be wrapped with ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode`` object and passed to ``loads()`` ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ return loads(fp.read(), encoding=encoding, cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, **kw) def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to ``unicode`` first. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN, null, true, false. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ if (cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and not kw): return _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant return cls(encoding=encoding, **kw).decode(s)
123danielbenjaminphilpott-123
simplejson/__init__.py
Python
asf20
12,503
r"""Using simplejson from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -msimplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -msimplejson.tool Expecting property name: line 1 column 2 (char 2) """ import simplejson def main(): import sys if len(sys.argv) == 1: infile = sys.stdin outfile = sys.stdout elif len(sys.argv) == 2: infile = open(sys.argv[1], 'rb') outfile = sys.stdout elif len(sys.argv) == 3: infile = open(sys.argv[1], 'rb') outfile = open(sys.argv[2], 'wb') else: raise SystemExit("%s [infile [outfile]]" % (sys.argv[0],)) try: obj = simplejson.load(infile) except ValueError, e: raise SystemExit(e) simplejson.dump(obj, outfile, sort_keys=True, indent=4) outfile.write('\n') if __name__ == '__main__': main()
123danielbenjaminphilpott-123
simplejson/tool.py
Python
asf20
908
<!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html><head><title>Python: module twitter</title> </head><body bgcolor="#f0f0f8"> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="heading"> <tr bgcolor="#7799ee"> <td valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial">&nbsp;<br><big><big><strong>twitter</strong></big></big> (version 0.8)</font></td ><td align=right valign=bottom ><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="twitter.py">twitter.py</a></font></td></tr></table> <p><tt>A&nbsp;library&nbsp;that&nbsp;provides&nbsp;a&nbsp;Python&nbsp;interface&nbsp;to&nbsp;the&nbsp;Twitter&nbsp;API</tt></p> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#aa55cc"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial"><big><strong>Modules</strong></big></font></td></tr> <tr><td bgcolor="#aa55cc"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%"><table width="100%" summary="list"><tr><td width="25%" valign=top><a href="StringIO.html">StringIO</a><br> <a href="base64.html">base64</a><br> <a href="calendar.html">calendar</a><br> <a href="datetime.html">datetime</a><br> <a href="gzip.html">gzip</a><br> </td><td width="25%" valign=top><a href="httplib.html">httplib</a><br> <a href="oauth2.html">oauth2</a><br> <a href="os.html">os</a><br> <a href="rfc822.html">rfc822</a><br> <a href="json.html">json</a><br> </td><td width="25%" valign=top><a href="sys.html">sys</a><br> <a href="tempfile.html">tempfile</a><br> <a href="textwrap.html">textwrap</a><br> <a href="time.html">time</a><br> <a href="urllib.html">urllib</a><br> </td><td width="25%" valign=top><a href="urllib2.html">urllib2</a><br> <a href="urlparse.html">urlparse</a><br> </td></tr></table></td></tr></table><p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ee77aa"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr> <tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%"><dl> <dt><font face="helvetica, arial"><a href="__builtin__.html#object">__builtin__.object</a> </font></dt><dd> <dl> <dt><font face="helvetica, arial"><a href="twitter.html#Api">Api</a> </font></dt><dt><font face="helvetica, arial"><a href="twitter.html#DirectMessage">DirectMessage</a> </font></dt><dt><font face="helvetica, arial"><a href="twitter.html#Hashtag">Hashtag</a> </font></dt><dt><font face="helvetica, arial"><a href="twitter.html#List">List</a> </font></dt><dt><font face="helvetica, arial"><a href="twitter.html#Status">Status</a> </font></dt><dt><font face="helvetica, arial"><a href="twitter.html#Trend">Trend</a> </font></dt><dt><font face="helvetica, arial"><a href="twitter.html#Url">Url</a> </font></dt><dt><font face="helvetica, arial"><a href="twitter.html#User">User</a> </font></dt></dl> </dd> <dt><font face="helvetica, arial"><a href="exceptions.html#Exception">exceptions.Exception</a>(<a href="exceptions.html#BaseException">exceptions.BaseException</a>) </font></dt><dd> <dl> <dt><font face="helvetica, arial"><a href="twitter.html#TwitterError">TwitterError</a> </font></dt></dl> </dd> </dl> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="Api">class <strong>Api</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr> <tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td> <td colspan=2><tt>A&nbsp;python&nbsp;interface&nbsp;into&nbsp;the&nbsp;Twitter&nbsp;API<br> &nbsp;<br> By&nbsp;default,&nbsp;the&nbsp;<a href="#Api">Api</a>&nbsp;caches&nbsp;results&nbsp;for&nbsp;1&nbsp;minute.<br> &nbsp;<br> Example&nbsp;usage:<br> &nbsp;<br> &nbsp;&nbsp;To&nbsp;create&nbsp;an&nbsp;instance&nbsp;of&nbsp;the&nbsp;twitter.<a href="#Api">Api</a>&nbsp;class,&nbsp;with&nbsp;no&nbsp;authentication:<br> &nbsp;<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;import&nbsp;twitter<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api&nbsp;=&nbsp;twitter.<a href="#Api">Api</a>()<br> &nbsp;<br> &nbsp;&nbsp;To&nbsp;fetch&nbsp;the&nbsp;most&nbsp;recently&nbsp;posted&nbsp;public&nbsp;twitter&nbsp;status&nbsp;messages:<br> &nbsp;<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;statuses&nbsp;=&nbsp;api.<a href="#Api-GetPublicTimeline">GetPublicTimeline</a>()<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;print&nbsp;[s.user.name&nbsp;for&nbsp;s&nbsp;in&nbsp;statuses]<br> &nbsp;&nbsp;&nbsp;&nbsp;[u'DeWitt',&nbsp;u'Kesuke&nbsp;Miyagi',&nbsp;u'ev',&nbsp;u'Buzz&nbsp;Andersen',&nbsp;u'Biz&nbsp;Stone']&nbsp;#...<br> &nbsp;<br> &nbsp;&nbsp;To&nbsp;fetch&nbsp;a&nbsp;single&nbsp;user's&nbsp;public&nbsp;status&nbsp;messages,&nbsp;where&nbsp;"user"&nbsp;is&nbsp;either<br> &nbsp;&nbsp;a&nbsp;Twitter&nbsp;"short&nbsp;name"&nbsp;or&nbsp;their&nbsp;user&nbsp;id.<br> &nbsp;<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;statuses&nbsp;=&nbsp;api.<a href="#Api-GetUserTimeline">GetUserTimeline</a>(user)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;print&nbsp;[s.text&nbsp;for&nbsp;s&nbsp;in&nbsp;statuses]<br> &nbsp;<br> &nbsp;&nbsp;To&nbsp;use&nbsp;authentication,&nbsp;instantiate&nbsp;the&nbsp;twitter.<a href="#Api">Api</a>&nbsp;class&nbsp;with&nbsp;a<br> &nbsp;&nbsp;consumer&nbsp;key&nbsp;and&nbsp;secret;&nbsp;and&nbsp;the&nbsp;oAuth&nbsp;key&nbsp;and&nbsp;secret:<br> &nbsp;<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api&nbsp;=&nbsp;twitter.<a href="#Api">Api</a>(consumer_key='twitter&nbsp;consumer&nbsp;key',<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;consumer_secret='twitter&nbsp;consumer&nbsp;secret',<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;access_token_key='the_key_given',<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;access_token_secret='the_key_secret')<br> &nbsp;<br> &nbsp;&nbsp;To&nbsp;fetch&nbsp;your&nbsp;friends&nbsp;(after&nbsp;being&nbsp;authenticated):<br> &nbsp;<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;users&nbsp;=&nbsp;api.<a href="#Api-GetFriends">GetFriends</a>()<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;print&nbsp;[u.name&nbsp;for&nbsp;u&nbsp;in&nbsp;users]<br> &nbsp;<br> &nbsp;&nbsp;To&nbsp;post&nbsp;a&nbsp;twitter&nbsp;status&nbsp;message&nbsp;(after&nbsp;being&nbsp;authenticated):<br> &nbsp;<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;status&nbsp;=&nbsp;api.<a href="#Api-PostUpdate">PostUpdate</a>('I&nbsp;love&nbsp;python-twitter!')<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;print&nbsp;status.text<br> &nbsp;&nbsp;&nbsp;&nbsp;I&nbsp;love&nbsp;python-twitter!<br> &nbsp;<br> &nbsp;&nbsp;There&nbsp;are&nbsp;many&nbsp;other&nbsp;methods,&nbsp;including:<br> &nbsp;<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-PostUpdates">PostUpdates</a>(status)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-PostDirectMessage">PostDirectMessage</a>(user,&nbsp;text)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-GetUser">GetUser</a>(user)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-GetReplies">GetReplies</a>()<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-GetUserTimeline">GetUserTimeline</a>(user)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-GetStatus">GetStatus</a>(id)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-DestroyStatus">DestroyStatus</a>(id)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-GetFriendsTimeline">GetFriendsTimeline</a>(user)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-GetFriends">GetFriends</a>(user)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-GetFollowers">GetFollowers</a>()<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-GetFeatured">GetFeatured</a>()<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-GetDirectMessages">GetDirectMessages</a>()<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-PostDirectMessage">PostDirectMessage</a>(user,&nbsp;text)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-DestroyDirectMessage">DestroyDirectMessage</a>(id)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-DestroyFriendship">DestroyFriendship</a>(user)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-CreateFriendship">CreateFriendship</a>(user)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-GetUserByEmail">GetUserByEmail</a>(email)<br> &nbsp;&nbsp;&nbsp;&nbsp;&gt;&gt;&gt;&nbsp;api.<a href="#Api-VerifyCredentials">VerifyCredentials</a>()<br>&nbsp;</tt></td></tr> <tr><td>&nbsp;</td> <td width="100%">Methods defined here:<br> <dl><dt><a name="Api-ClearCredentials"><strong>ClearCredentials</strong></a>(self)</dt><dd><tt>Clear&nbsp;the&nbsp;any&nbsp;credentials&nbsp;for&nbsp;this&nbsp;instance</tt></dd></dl> <dl><dt><a name="Api-CreateFavorite"><strong>CreateFavorite</strong></a>(self, status)</dt><dd><tt>Favorites&nbsp;the&nbsp;status&nbsp;specified&nbsp;in&nbsp;the&nbsp;status&nbsp;parameter&nbsp;as&nbsp;the&nbsp;authenticating&nbsp;user.<br> Returns&nbsp;the&nbsp;favorite&nbsp;status&nbsp;when&nbsp;successful.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;The&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance&nbsp;to&nbsp;mark&nbsp;as&nbsp;a&nbsp;favorite.<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;newly-marked&nbsp;favorite.</tt></dd></dl> <dl><dt><a name="Api-CreateFriendship"><strong>CreateFriendship</strong></a>(self, user)</dt><dd><tt>Befriends&nbsp;the&nbsp;user&nbsp;specified&nbsp;in&nbsp;the&nbsp;user&nbsp;parameter&nbsp;as&nbsp;the&nbsp;authenticating&nbsp;user.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;The&nbsp;ID&nbsp;or&nbsp;screen&nbsp;name&nbsp;of&nbsp;the&nbsp;user&nbsp;to&nbsp;befriend.<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#User">User</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;befriended&nbsp;user.</tt></dd></dl> <dl><dt><a name="Api-CreateList"><strong>CreateList</strong></a>(self, user, name, mode<font color="#909090">=None</font>, description<font color="#909090">=None</font>)</dt><dd><tt>Creates&nbsp;a&nbsp;new&nbsp;list&nbsp;with&nbsp;the&nbsp;give&nbsp;name<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user:<br> &nbsp;&nbsp;&nbsp;&nbsp;Twitter&nbsp;name&nbsp;to&nbsp;create&nbsp;the&nbsp;list&nbsp;for<br> &nbsp;&nbsp;name:<br> &nbsp;&nbsp;&nbsp;&nbsp;New&nbsp;name&nbsp;for&nbsp;the&nbsp;list<br> &nbsp;&nbsp;mode:<br> &nbsp;&nbsp;&nbsp;&nbsp;'public'&nbsp;or&nbsp;'private'.<br> &nbsp;&nbsp;&nbsp;&nbsp;Defaults&nbsp;to&nbsp;'public'.&nbsp;[Optional]<br> &nbsp;&nbsp;description:<br> &nbsp;&nbsp;&nbsp;&nbsp;Description&nbsp;of&nbsp;the&nbsp;list.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#List">List</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;new&nbsp;list</tt></dd></dl> <dl><dt><a name="Api-CreateSubscription"><strong>CreateSubscription</strong></a>(self, owner, list)</dt><dd><tt>Creates&nbsp;a&nbsp;subscription&nbsp;to&nbsp;a&nbsp;list&nbsp;by&nbsp;the&nbsp;authenticated&nbsp;user<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;owner:<br> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#User">User</a>&nbsp;name&nbsp;or&nbsp;id&nbsp;of&nbsp;the&nbsp;owner&nbsp;of&nbsp;the&nbsp;list&nbsp;being&nbsp;subscribed&nbsp;to.<br> &nbsp;&nbsp;list:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;slug&nbsp;or&nbsp;list&nbsp;id&nbsp;to&nbsp;subscribe&nbsp;the&nbsp;user&nbsp;to<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#List">List</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;list&nbsp;subscribed&nbsp;to</tt></dd></dl> <dl><dt><a name="Api-DestroyDirectMessage"><strong>DestroyDirectMessage</strong></a>(self, id)</dt><dd><tt>Destroys&nbsp;the&nbsp;direct&nbsp;message&nbsp;specified&nbsp;in&nbsp;the&nbsp;required&nbsp;ID&nbsp;parameter.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated,&nbsp;and&nbsp;the<br> authenticating&nbsp;user&nbsp;must&nbsp;be&nbsp;the&nbsp;recipient&nbsp;of&nbsp;the&nbsp;specified&nbsp;direct<br> message.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;id:&nbsp;The&nbsp;id&nbsp;of&nbsp;the&nbsp;direct&nbsp;message&nbsp;to&nbsp;be&nbsp;destroyed<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#DirectMessage">DirectMessage</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;message&nbsp;destroyed</tt></dd></dl> <dl><dt><a name="Api-DestroyFavorite"><strong>DestroyFavorite</strong></a>(self, status)</dt><dd><tt>Un-favorites&nbsp;the&nbsp;status&nbsp;specified&nbsp;in&nbsp;the&nbsp;ID&nbsp;parameter&nbsp;as&nbsp;the&nbsp;authenticating&nbsp;user.<br> Returns&nbsp;the&nbsp;un-favorited&nbsp;status&nbsp;in&nbsp;the&nbsp;requested&nbsp;format&nbsp;when&nbsp;successful.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;The&nbsp;twitter.<a href="#Status">Status</a>&nbsp;to&nbsp;unmark&nbsp;as&nbsp;a&nbsp;favorite.<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;newly-unmarked&nbsp;favorite.</tt></dd></dl> <dl><dt><a name="Api-DestroyFriendship"><strong>DestroyFriendship</strong></a>(self, user)</dt><dd><tt>Discontinues&nbsp;friendship&nbsp;with&nbsp;the&nbsp;user&nbsp;specified&nbsp;in&nbsp;the&nbsp;user&nbsp;parameter.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;The&nbsp;ID&nbsp;or&nbsp;screen&nbsp;name&nbsp;of&nbsp;the&nbsp;user&nbsp;&nbsp;with&nbsp;whom&nbsp;to&nbsp;discontinue&nbsp;friendship.<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#User">User</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;discontinued&nbsp;friend.</tt></dd></dl> <dl><dt><a name="Api-DestroyList"><strong>DestroyList</strong></a>(self, user, id)</dt><dd><tt>Destroys&nbsp;the&nbsp;list&nbsp;from&nbsp;the&nbsp;given&nbsp;user<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;user&nbsp;to&nbsp;remove&nbsp;the&nbsp;list&nbsp;from.<br> &nbsp;&nbsp;id:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;slug&nbsp;or&nbsp;id&nbsp;of&nbsp;the&nbsp;list&nbsp;to&nbsp;remove.<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#List">List</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;removed&nbsp;list.</tt></dd></dl> <dl><dt><a name="Api-DestroyStatus"><strong>DestroyStatus</strong></a>(self, id)</dt><dd><tt>Destroys&nbsp;the&nbsp;status&nbsp;specified&nbsp;by&nbsp;the&nbsp;required&nbsp;ID&nbsp;parameter.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated&nbsp;and&nbsp;the<br> authenticating&nbsp;user&nbsp;must&nbsp;be&nbsp;the&nbsp;author&nbsp;of&nbsp;the&nbsp;specified&nbsp;status.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;id:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;numerical&nbsp;ID&nbsp;of&nbsp;the&nbsp;status&nbsp;you're&nbsp;trying&nbsp;to&nbsp;destroy.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;destroyed&nbsp;status&nbsp;message</tt></dd></dl> <dl><dt><a name="Api-DestroySubscription"><strong>DestroySubscription</strong></a>(self, owner, list)</dt><dd><tt>Destroys&nbsp;the&nbsp;subscription&nbsp;to&nbsp;a&nbsp;list&nbsp;for&nbsp;the&nbsp;authenticated&nbsp;user<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;owner:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;user&nbsp;id&nbsp;or&nbsp;screen&nbsp;name&nbsp;of&nbsp;the&nbsp;user&nbsp;that&nbsp;owns&nbsp;the<br> &nbsp;&nbsp;&nbsp;&nbsp;list&nbsp;that&nbsp;is&nbsp;to&nbsp;be&nbsp;unsubscribed&nbsp;from<br> &nbsp;&nbsp;list:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;slug&nbsp;or&nbsp;list&nbsp;id&nbsp;of&nbsp;the&nbsp;list&nbsp;to&nbsp;unsubscribe&nbsp;from<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#List">List</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;removed&nbsp;list.</tt></dd></dl> <dl><dt><a name="Api-FilterPublicTimeline"><strong>FilterPublicTimeline</strong></a>(self, term, since_id<font color="#909090">=None</font>)</dt><dd><tt>Filter&nbsp;the&nbsp;public&nbsp;twitter&nbsp;timeline&nbsp;by&nbsp;a&nbsp;given&nbsp;search&nbsp;term&nbsp;on<br> the&nbsp;local&nbsp;machine.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;term:<br> &nbsp;&nbsp;&nbsp;&nbsp;term&nbsp;to&nbsp;search&nbsp;by.<br> &nbsp;&nbsp;since_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Returns&nbsp;results&nbsp;with&nbsp;an&nbsp;ID&nbsp;greater&nbsp;than&nbsp;(that&nbsp;is,&nbsp;more&nbsp;recent<br> &nbsp;&nbsp;&nbsp;&nbsp;than)&nbsp;the&nbsp;specified&nbsp;ID.&nbsp;There&nbsp;are&nbsp;limits&nbsp;to&nbsp;the&nbsp;number&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;which&nbsp;can&nbsp;be&nbsp;accessed&nbsp;through&nbsp;the&nbsp;API.&nbsp;If&nbsp;the&nbsp;limit&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;has&nbsp;occured&nbsp;since&nbsp;the&nbsp;since_id,&nbsp;the&nbsp;since_id&nbsp;will&nbsp;be<br> &nbsp;&nbsp;&nbsp;&nbsp;forced&nbsp;to&nbsp;the&nbsp;oldest&nbsp;ID&nbsp;available.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;message<br> &nbsp;&nbsp;containing&nbsp;the&nbsp;term</tt></dd></dl> <dl><dt><a name="Api-GetDirectMessages"><strong>GetDirectMessages</strong></a>(self, since<font color="#909090">=None</font>, since_id<font color="#909090">=None</font>, page<font color="#909090">=None</font>)</dt><dd><tt>Returns&nbsp;a&nbsp;list&nbsp;of&nbsp;the&nbsp;direct&nbsp;messages&nbsp;sent&nbsp;to&nbsp;the&nbsp;authenticating&nbsp;user.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;since:<br> &nbsp;&nbsp;&nbsp;&nbsp;Narrows&nbsp;the&nbsp;returned&nbsp;results&nbsp;to&nbsp;just&nbsp;those&nbsp;statuses&nbsp;created<br> &nbsp;&nbsp;&nbsp;&nbsp;after&nbsp;the&nbsp;specified&nbsp;HTTP-formatted&nbsp;date.&nbsp;[Optional]<br> &nbsp;&nbsp;since_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Returns&nbsp;results&nbsp;with&nbsp;an&nbsp;ID&nbsp;greater&nbsp;than&nbsp;(that&nbsp;is,&nbsp;more&nbsp;recent<br> &nbsp;&nbsp;&nbsp;&nbsp;than)&nbsp;the&nbsp;specified&nbsp;ID.&nbsp;There&nbsp;are&nbsp;limits&nbsp;to&nbsp;the&nbsp;number&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;which&nbsp;can&nbsp;be&nbsp;accessed&nbsp;through&nbsp;the&nbsp;API.&nbsp;If&nbsp;the&nbsp;limit&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;has&nbsp;occured&nbsp;since&nbsp;the&nbsp;since_id,&nbsp;the&nbsp;since_id&nbsp;will&nbsp;be<br> &nbsp;&nbsp;&nbsp;&nbsp;forced&nbsp;to&nbsp;the&nbsp;oldest&nbsp;ID&nbsp;available.&nbsp;[Optional]<br> &nbsp;&nbsp;page:<br> &nbsp;&nbsp;&nbsp;&nbsp;Specifies&nbsp;the&nbsp;page&nbsp;of&nbsp;results&nbsp;to&nbsp;retrieve.<br> &nbsp;&nbsp;&nbsp;&nbsp;Note:&nbsp;there&nbsp;are&nbsp;pagination&nbsp;limits.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#DirectMessage">DirectMessage</a>&nbsp;instances</tt></dd></dl> <dl><dt><a name="Api-GetFavorites"><strong>GetFavorites</strong></a>(self, user<font color="#909090">=None</font>, page<font color="#909090">=None</font>)</dt><dd><tt>Return&nbsp;a&nbsp;list&nbsp;of&nbsp;<a href="#Status">Status</a>&nbsp;objects&nbsp;representing&nbsp;favorited&nbsp;tweets.<br> By&nbsp;default,&nbsp;returns&nbsp;the&nbsp;(up&nbsp;to)&nbsp;20&nbsp;most&nbsp;recent&nbsp;tweets&nbsp;for&nbsp;the<br> authenticated&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;twitter&nbsp;name&nbsp;or&nbsp;id&nbsp;of&nbsp;the&nbsp;user&nbsp;whose&nbsp;favorites&nbsp;you&nbsp;are&nbsp;fetching.<br> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;not&nbsp;specified,&nbsp;defaults&nbsp;to&nbsp;the&nbsp;authenticated&nbsp;user.&nbsp;[Optional]<br> &nbsp;&nbsp;page:<br> &nbsp;&nbsp;&nbsp;&nbsp;Specifies&nbsp;the&nbsp;page&nbsp;of&nbsp;results&nbsp;to&nbsp;retrieve.<br> &nbsp;&nbsp;&nbsp;&nbsp;Note:&nbsp;there&nbsp;are&nbsp;pagination&nbsp;limits.&nbsp;[Optional]</tt></dd></dl> <dl><dt><a name="Api-GetFeatured"><strong>GetFeatured</strong></a>(self)</dt><dd><tt>Fetch&nbsp;the&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#User">User</a>&nbsp;instances&nbsp;featured&nbsp;on&nbsp;twitter.com<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#User">User</a>&nbsp;instances</tt></dd></dl> <dl><dt><a name="Api-GetFollowerIDs"><strong>GetFollowerIDs</strong></a>(self, userid<font color="#909090">=None</font>, cursor<font color="#909090">=-1</font>)</dt><dd><tt>Fetch&nbsp;the&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#User">User</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;follower<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#User">User</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;follower</tt></dd></dl> <dl><dt><a name="Api-GetFollowers"><strong>GetFollowers</strong></a>(self, page<font color="#909090">=None</font>)</dt><dd><tt>Fetch&nbsp;the&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#User">User</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;follower<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;page:<br> &nbsp;&nbsp;&nbsp;&nbsp;Specifies&nbsp;the&nbsp;page&nbsp;of&nbsp;results&nbsp;to&nbsp;retrieve.<br> &nbsp;&nbsp;&nbsp;&nbsp;Note:&nbsp;there&nbsp;are&nbsp;pagination&nbsp;limits.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#User">User</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;follower</tt></dd></dl> <dl><dt><a name="Api-GetFriendIDs"><strong>GetFriendIDs</strong></a>(self, user<font color="#909090">=None</font>, cursor<font color="#909090">=-1</font>)</dt><dd><tt>Returns&nbsp;a&nbsp;list&nbsp;of&nbsp;twitter&nbsp;user&nbsp;id's&nbsp;for&nbsp;every&nbsp;person<br> the&nbsp;specified&nbsp;user&nbsp;is&nbsp;following.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;id&nbsp;or&nbsp;screen_name&nbsp;of&nbsp;the&nbsp;user&nbsp;to&nbsp;retrieve&nbsp;the&nbsp;id&nbsp;list&nbsp;for<br> &nbsp;&nbsp;&nbsp;&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;list&nbsp;of&nbsp;integers,&nbsp;one&nbsp;for&nbsp;each&nbsp;user&nbsp;id.</tt></dd></dl> <dl><dt><a name="Api-GetFriends"><strong>GetFriends</strong></a>(self, user<font color="#909090">=None</font>, cursor<font color="#909090">=-1</font>)</dt><dd><tt>Fetch&nbsp;the&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#User">User</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;friend.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;twitter&nbsp;name&nbsp;or&nbsp;id&nbsp;of&nbsp;the&nbsp;user&nbsp;whose&nbsp;friends&nbsp;you&nbsp;are&nbsp;fetching.<br> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;not&nbsp;specified,&nbsp;defaults&nbsp;to&nbsp;the&nbsp;authenticated&nbsp;user.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#User">User</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;friend</tt></dd></dl> <dl><dt><a name="Api-GetFriendsTimeline"><strong>GetFriendsTimeline</strong></a>(self, user<font color="#909090">=None</font>, count<font color="#909090">=None</font>, page<font color="#909090">=None</font>, since_id<font color="#909090">=None</font>, retweets<font color="#909090">=None</font>, include_entities<font color="#909090">=None</font>)</dt><dd><tt>Fetch&nbsp;the&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#Status">Status</a>&nbsp;messages&nbsp;for&nbsp;a&nbsp;user's&nbsp;friends<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated&nbsp;if&nbsp;the&nbsp;user&nbsp;is&nbsp;private.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user:<br> &nbsp;&nbsp;&nbsp;&nbsp;Specifies&nbsp;the&nbsp;ID&nbsp;or&nbsp;screen&nbsp;name&nbsp;of&nbsp;the&nbsp;user&nbsp;for&nbsp;whom&nbsp;to&nbsp;return<br> &nbsp;&nbsp;&nbsp;&nbsp;the&nbsp;friends_timeline.&nbsp;&nbsp;If&nbsp;not&nbsp;specified&nbsp;then&nbsp;the&nbsp;authenticated<br> &nbsp;&nbsp;&nbsp;&nbsp;user&nbsp;set&nbsp;in&nbsp;the&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;will&nbsp;be&nbsp;used.&nbsp;&nbsp;[Optional]<br> &nbsp;&nbsp;count:<br> &nbsp;&nbsp;&nbsp;&nbsp;Specifies&nbsp;the&nbsp;number&nbsp;of&nbsp;statuses&nbsp;to&nbsp;retrieve.&nbsp;May&nbsp;not&nbsp;be<br> &nbsp;&nbsp;&nbsp;&nbsp;greater&nbsp;than&nbsp;100.&nbsp;[Optional]<br> &nbsp;&nbsp;page:<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Specifies&nbsp;the&nbsp;page&nbsp;of&nbsp;results&nbsp;to&nbsp;retrieve.<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Note:&nbsp;there&nbsp;are&nbsp;pagination&nbsp;limits.&nbsp;[Optional]<br> &nbsp;&nbsp;since_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Returns&nbsp;results&nbsp;with&nbsp;an&nbsp;ID&nbsp;greater&nbsp;than&nbsp;(that&nbsp;is,&nbsp;more&nbsp;recent<br> &nbsp;&nbsp;&nbsp;&nbsp;than)&nbsp;the&nbsp;specified&nbsp;ID.&nbsp;There&nbsp;are&nbsp;limits&nbsp;to&nbsp;the&nbsp;number&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;which&nbsp;can&nbsp;be&nbsp;accessed&nbsp;through&nbsp;the&nbsp;API.&nbsp;If&nbsp;the&nbsp;limit&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;has&nbsp;occured&nbsp;since&nbsp;the&nbsp;since_id,&nbsp;the&nbsp;since_id&nbsp;will&nbsp;be<br> &nbsp;&nbsp;&nbsp;&nbsp;forced&nbsp;to&nbsp;the&nbsp;oldest&nbsp;ID&nbsp;available.&nbsp;[Optional]<br> &nbsp;&nbsp;retweets:<br> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;True,&nbsp;the&nbsp;timeline&nbsp;will&nbsp;contain&nbsp;native&nbsp;retweets.&nbsp;[Optional]<br> &nbsp;&nbsp;include_entities:<br> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;True,&nbsp;each&nbsp;tweet&nbsp;will&nbsp;include&nbsp;a&nbsp;node&nbsp;called&nbsp;"entities,".<br> &nbsp;&nbsp;&nbsp;&nbsp;This&nbsp;node&nbsp;offers&nbsp;a&nbsp;variety&nbsp;of&nbsp;metadata&nbsp;about&nbsp;the&nbsp;tweet&nbsp;in&nbsp;a<br> &nbsp;&nbsp;&nbsp;&nbsp;discreet&nbsp;structure,&nbsp;including:&nbsp;user_mentions,&nbsp;urls,&nbsp;and<br> &nbsp;&nbsp;&nbsp;&nbsp;hashtags.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;message</tt></dd></dl> <dl><dt><a name="Api-GetLists"><strong>GetLists</strong></a>(self, user, cursor<font color="#909090">=-1</font>)</dt><dd><tt>Fetch&nbsp;the&nbsp;sequence&nbsp;of&nbsp;lists&nbsp;for&nbsp;a&nbsp;user.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;twitter&nbsp;name&nbsp;or&nbsp;id&nbsp;of&nbsp;the&nbsp;user&nbsp;whose&nbsp;friends&nbsp;you&nbsp;are&nbsp;fetching.<br> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;the&nbsp;passed&nbsp;in&nbsp;user&nbsp;is&nbsp;the&nbsp;same&nbsp;as&nbsp;the&nbsp;authenticated&nbsp;user<br> &nbsp;&nbsp;&nbsp;&nbsp;then&nbsp;you&nbsp;will&nbsp;also&nbsp;receive&nbsp;private&nbsp;list&nbsp;data.<br> &nbsp;&nbsp;cursor:<br> &nbsp;&nbsp;&nbsp;&nbsp;"page"&nbsp;value&nbsp;that&nbsp;Twitter&nbsp;will&nbsp;use&nbsp;to&nbsp;start&nbsp;building&nbsp;the<br> &nbsp;&nbsp;&nbsp;&nbsp;list&nbsp;sequence&nbsp;from.&nbsp;&nbsp;-1&nbsp;to&nbsp;start&nbsp;at&nbsp;the&nbsp;beginning.<br> &nbsp;&nbsp;&nbsp;&nbsp;Twitter&nbsp;will&nbsp;return&nbsp;in&nbsp;the&nbsp;result&nbsp;the&nbsp;values&nbsp;for&nbsp;next_cursor<br> &nbsp;&nbsp;&nbsp;&nbsp;and&nbsp;previous_cursor.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#List">List</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;list</tt></dd></dl> <dl><dt><a name="Api-GetMentions"><strong>GetMentions</strong></a>(self, since_id<font color="#909090">=None</font>, max_id<font color="#909090">=None</font>, page<font color="#909090">=None</font>)</dt><dd><tt>Returns&nbsp;the&nbsp;20&nbsp;most&nbsp;recent&nbsp;mentions&nbsp;(status&nbsp;containing&nbsp;@twitterID)<br> for&nbsp;the&nbsp;authenticating&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;since_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Returns&nbsp;results&nbsp;with&nbsp;an&nbsp;ID&nbsp;greater&nbsp;than&nbsp;(that&nbsp;is,&nbsp;more&nbsp;recent<br> &nbsp;&nbsp;&nbsp;&nbsp;than)&nbsp;the&nbsp;specified&nbsp;ID.&nbsp;There&nbsp;are&nbsp;limits&nbsp;to&nbsp;the&nbsp;number&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;which&nbsp;can&nbsp;be&nbsp;accessed&nbsp;through&nbsp;the&nbsp;API.&nbsp;If&nbsp;the&nbsp;limit&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;has&nbsp;occured&nbsp;since&nbsp;the&nbsp;since_id,&nbsp;the&nbsp;since_id&nbsp;will&nbsp;be<br> &nbsp;&nbsp;&nbsp;&nbsp;forced&nbsp;to&nbsp;the&nbsp;oldest&nbsp;ID&nbsp;available.&nbsp;[Optional]<br> &nbsp;&nbsp;max_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Returns&nbsp;only&nbsp;statuses&nbsp;with&nbsp;an&nbsp;ID&nbsp;less&nbsp;than<br> &nbsp;&nbsp;&nbsp;&nbsp;(that&nbsp;is,&nbsp;older&nbsp;than)&nbsp;the&nbsp;specified&nbsp;ID.&nbsp;&nbsp;[Optional]<br> &nbsp;&nbsp;page:<br> &nbsp;&nbsp;&nbsp;&nbsp;Specifies&nbsp;the&nbsp;page&nbsp;of&nbsp;results&nbsp;to&nbsp;retrieve.<br> &nbsp;&nbsp;&nbsp;&nbsp;Note:&nbsp;there&nbsp;are&nbsp;pagination&nbsp;limits.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;mention&nbsp;of&nbsp;the&nbsp;user.</tt></dd></dl> <dl><dt><a name="Api-GetPublicTimeline"><strong>GetPublicTimeline</strong></a>(self, since_id<font color="#909090">=None</font>, include_rts<font color="#909090">=None</font>, include_entities<font color="#909090">=None</font>)</dt><dd><tt>Fetch&nbsp;the&nbsp;sequence&nbsp;of&nbsp;public&nbsp;twitter.<a href="#Status">Status</a>&nbsp;message&nbsp;for&nbsp;all&nbsp;users.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;since_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Returns&nbsp;results&nbsp;with&nbsp;an&nbsp;ID&nbsp;greater&nbsp;than&nbsp;(that&nbsp;is,&nbsp;more&nbsp;recent<br> &nbsp;&nbsp;&nbsp;&nbsp;than)&nbsp;the&nbsp;specified&nbsp;ID.&nbsp;There&nbsp;are&nbsp;limits&nbsp;to&nbsp;the&nbsp;number&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;which&nbsp;can&nbsp;be&nbsp;accessed&nbsp;through&nbsp;the&nbsp;API.&nbsp;If&nbsp;the&nbsp;limit&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;has&nbsp;occured&nbsp;since&nbsp;the&nbsp;since_id,&nbsp;the&nbsp;since_id&nbsp;will&nbsp;be<br> &nbsp;&nbsp;&nbsp;&nbsp;forced&nbsp;to&nbsp;the&nbsp;oldest&nbsp;ID&nbsp;available.&nbsp;[Optional]<br> &nbsp;&nbsp;include_rts:<br> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;True,&nbsp;the&nbsp;timeline&nbsp;will&nbsp;contain&nbsp;native&nbsp;retweets&nbsp;(if&nbsp;they<br> &nbsp;&nbsp;&nbsp;&nbsp;exist)&nbsp;in&nbsp;addition&nbsp;to&nbsp;the&nbsp;standard&nbsp;stream&nbsp;of&nbsp;tweets.&nbsp;[Optional]<br> &nbsp;&nbsp;include_entities:<br> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;True,&nbsp;each&nbsp;tweet&nbsp;will&nbsp;include&nbsp;a&nbsp;node&nbsp;called&nbsp;"entities,".<br> &nbsp;&nbsp;&nbsp;&nbsp;This&nbsp;node&nbsp;offers&nbsp;a&nbsp;variety&nbsp;of&nbsp;metadata&nbsp;about&nbsp;the&nbsp;tweet&nbsp;in&nbsp;a<br> &nbsp;&nbsp;&nbsp;&nbsp;discreet&nbsp;structure,&nbsp;including:&nbsp;user_mentions,&nbsp;urls,&nbsp;and<br> &nbsp;&nbsp;&nbsp;&nbsp;hashtags.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;An&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;message</tt></dd></dl> <dl><dt><a name="Api-GetRateLimitStatus"><strong>GetRateLimitStatus</strong></a>(self)</dt><dd><tt>Fetch&nbsp;the&nbsp;rate&nbsp;limit&nbsp;status&nbsp;for&nbsp;the&nbsp;currently&nbsp;authorized&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;dictionary&nbsp;containing&nbsp;the&nbsp;time&nbsp;the&nbsp;limit&nbsp;will&nbsp;reset&nbsp;(reset_time),<br> &nbsp;&nbsp;the&nbsp;number&nbsp;of&nbsp;remaining&nbsp;hits&nbsp;allowed&nbsp;before&nbsp;the&nbsp;reset&nbsp;(remaining_hits),<br> &nbsp;&nbsp;the&nbsp;number&nbsp;of&nbsp;hits&nbsp;allowed&nbsp;in&nbsp;a&nbsp;60-minute&nbsp;period&nbsp;(hourly_limit),&nbsp;and<br> &nbsp;&nbsp;the&nbsp;time&nbsp;of&nbsp;the&nbsp;reset&nbsp;in&nbsp;seconds&nbsp;since&nbsp;The&nbsp;Epoch&nbsp;(reset_time_in_seconds).</tt></dd></dl> <dl><dt><a name="Api-GetReplies"><strong>GetReplies</strong></a>(self, since<font color="#909090">=None</font>, since_id<font color="#909090">=None</font>, page<font color="#909090">=None</font>)</dt><dd><tt>Get&nbsp;a&nbsp;sequence&nbsp;of&nbsp;status&nbsp;messages&nbsp;representing&nbsp;the&nbsp;20&nbsp;most<br> recent&nbsp;replies&nbsp;(status&nbsp;updates&nbsp;prefixed&nbsp;with&nbsp;@twitterID)&nbsp;to&nbsp;the<br> authenticating&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;since_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Returns&nbsp;results&nbsp;with&nbsp;an&nbsp;ID&nbsp;greater&nbsp;than&nbsp;(that&nbsp;is,&nbsp;more&nbsp;recent<br> &nbsp;&nbsp;&nbsp;&nbsp;than)&nbsp;the&nbsp;specified&nbsp;ID.&nbsp;There&nbsp;are&nbsp;limits&nbsp;to&nbsp;the&nbsp;number&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;which&nbsp;can&nbsp;be&nbsp;accessed&nbsp;through&nbsp;the&nbsp;API.&nbsp;If&nbsp;the&nbsp;limit&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;has&nbsp;occured&nbsp;since&nbsp;the&nbsp;since_id,&nbsp;the&nbsp;since_id&nbsp;will&nbsp;be<br> &nbsp;&nbsp;&nbsp;&nbsp;forced&nbsp;to&nbsp;the&nbsp;oldest&nbsp;ID&nbsp;available.&nbsp;[Optional]<br> &nbsp;&nbsp;page:<br> &nbsp;&nbsp;&nbsp;&nbsp;Specifies&nbsp;the&nbsp;page&nbsp;of&nbsp;results&nbsp;to&nbsp;retrieve.<br> &nbsp;&nbsp;&nbsp;&nbsp;Note:&nbsp;there&nbsp;are&nbsp;pagination&nbsp;limits.&nbsp;[Optional]<br> &nbsp;&nbsp;since:<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;reply&nbsp;to&nbsp;the&nbsp;user.</tt></dd></dl> <dl><dt><a name="Api-GetRetweets"><strong>GetRetweets</strong></a>(self, statusid)</dt><dd><tt>Returns&nbsp;up&nbsp;to&nbsp;100&nbsp;of&nbsp;the&nbsp;first&nbsp;retweets&nbsp;of&nbsp;the&nbsp;tweet&nbsp;identified<br> by&nbsp;statusid<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;statusid:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;ID&nbsp;of&nbsp;the&nbsp;tweet&nbsp;for&nbsp;which&nbsp;retweets&nbsp;should&nbsp;be&nbsp;searched&nbsp;for<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;list&nbsp;of&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instances,&nbsp;which&nbsp;are&nbsp;retweets&nbsp;of&nbsp;statusid</tt></dd></dl> <dl><dt><a name="Api-GetSearch"><strong>GetSearch</strong></a>(self, term, geocode<font color="#909090">=None</font>, since_id<font color="#909090">=None</font>, per_page<font color="#909090">=15</font>, page<font color="#909090">=1</font>, lang<font color="#909090">='en'</font>, show_user<font color="#909090">='true'</font>, query_users<font color="#909090">=False</font>)</dt><dd><tt>Return&nbsp;twitter&nbsp;search&nbsp;results&nbsp;for&nbsp;a&nbsp;given&nbsp;term.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;term:<br> &nbsp;&nbsp;&nbsp;&nbsp;term&nbsp;to&nbsp;search&nbsp;by.<br> &nbsp;&nbsp;since_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Returns&nbsp;results&nbsp;with&nbsp;an&nbsp;ID&nbsp;greater&nbsp;than&nbsp;(that&nbsp;is,&nbsp;more&nbsp;recent<br> &nbsp;&nbsp;&nbsp;&nbsp;than)&nbsp;the&nbsp;specified&nbsp;ID.&nbsp;There&nbsp;are&nbsp;limits&nbsp;to&nbsp;the&nbsp;number&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;which&nbsp;can&nbsp;be&nbsp;accessed&nbsp;through&nbsp;the&nbsp;API.&nbsp;If&nbsp;the&nbsp;limit&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;has&nbsp;occured&nbsp;since&nbsp;the&nbsp;since_id,&nbsp;the&nbsp;since_id&nbsp;will&nbsp;be<br> &nbsp;&nbsp;&nbsp;&nbsp;forced&nbsp;to&nbsp;the&nbsp;oldest&nbsp;ID&nbsp;available.&nbsp;[Optional]<br> &nbsp;&nbsp;geocode:<br> &nbsp;&nbsp;&nbsp;&nbsp;geolocation&nbsp;information&nbsp;in&nbsp;the&nbsp;form&nbsp;(latitude,&nbsp;longitude,&nbsp;radius)<br> &nbsp;&nbsp;&nbsp;&nbsp;[Optional]<br> &nbsp;&nbsp;per_page:<br> &nbsp;&nbsp;&nbsp;&nbsp;number&nbsp;of&nbsp;results&nbsp;to&nbsp;return.&nbsp;&nbsp;Default&nbsp;is&nbsp;15&nbsp;[Optional]<br> &nbsp;&nbsp;page:<br> &nbsp;&nbsp;&nbsp;&nbsp;Specifies&nbsp;the&nbsp;page&nbsp;of&nbsp;results&nbsp;to&nbsp;retrieve.<br> &nbsp;&nbsp;&nbsp;&nbsp;Note:&nbsp;there&nbsp;are&nbsp;pagination&nbsp;limits.&nbsp;[Optional]<br> &nbsp;&nbsp;lang:<br> &nbsp;&nbsp;&nbsp;&nbsp;language&nbsp;for&nbsp;results.&nbsp;&nbsp;Default&nbsp;is&nbsp;English&nbsp;[Optional]<br> &nbsp;&nbsp;show_user:<br> &nbsp;&nbsp;&nbsp;&nbsp;prefixes&nbsp;screen&nbsp;name&nbsp;in&nbsp;status<br> &nbsp;&nbsp;query_users:<br> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;set&nbsp;to&nbsp;False,&nbsp;then&nbsp;all&nbsp;users&nbsp;only&nbsp;have&nbsp;screen_name&nbsp;and<br> &nbsp;&nbsp;&nbsp;&nbsp;profile_image_url&nbsp;available.<br> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;set&nbsp;to&nbsp;True,&nbsp;all&nbsp;information&nbsp;of&nbsp;users&nbsp;are&nbsp;available,<br> &nbsp;&nbsp;&nbsp;&nbsp;but&nbsp;it&nbsp;uses&nbsp;lots&nbsp;of&nbsp;request&nbsp;quota,&nbsp;one&nbsp;per&nbsp;status.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;message&nbsp;containing<br> &nbsp;&nbsp;the&nbsp;term</tt></dd></dl> <dl><dt><a name="Api-GetStatus"><strong>GetStatus</strong></a>(self, id)</dt><dd><tt>Returns&nbsp;a&nbsp;single&nbsp;status&nbsp;message.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated&nbsp;if&nbsp;the<br> status&nbsp;message&nbsp;is&nbsp;private.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;id:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;numeric&nbsp;ID&nbsp;of&nbsp;the&nbsp;status&nbsp;you&nbsp;are&nbsp;trying&nbsp;to&nbsp;retrieve.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance&nbsp;representing&nbsp;that&nbsp;status&nbsp;message</tt></dd></dl> <dl><dt><a name="Api-GetSubscriptions"><strong>GetSubscriptions</strong></a>(self, user, cursor<font color="#909090">=-1</font>)</dt><dd><tt>Fetch&nbsp;the&nbsp;sequence&nbsp;of&nbsp;Lists&nbsp;that&nbsp;the&nbsp;given&nbsp;user&nbsp;is&nbsp;subscribed&nbsp;to<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;twitter&nbsp;name&nbsp;or&nbsp;id&nbsp;of&nbsp;the&nbsp;user<br> &nbsp;&nbsp;cursor:<br> &nbsp;&nbsp;&nbsp;&nbsp;"page"&nbsp;value&nbsp;that&nbsp;Twitter&nbsp;will&nbsp;use&nbsp;to&nbsp;start&nbsp;building&nbsp;the<br> &nbsp;&nbsp;&nbsp;&nbsp;list&nbsp;sequence&nbsp;from.&nbsp;&nbsp;-1&nbsp;to&nbsp;start&nbsp;at&nbsp;the&nbsp;beginning.<br> &nbsp;&nbsp;&nbsp;&nbsp;Twitter&nbsp;will&nbsp;return&nbsp;in&nbsp;the&nbsp;result&nbsp;the&nbsp;values&nbsp;for&nbsp;next_cursor<br> &nbsp;&nbsp;&nbsp;&nbsp;and&nbsp;previous_cursor.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#List">List</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;list</tt></dd></dl> <dl><dt><a name="Api-GetTrendsCurrent"><strong>GetTrendsCurrent</strong></a>(self, exclude<font color="#909090">=None</font>)</dt><dd><tt>Get&nbsp;the&nbsp;current&nbsp;top&nbsp;trending&nbsp;topics<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;exclude:<br> &nbsp;&nbsp;&nbsp;&nbsp;Appends&nbsp;the&nbsp;exclude&nbsp;parameter&nbsp;as&nbsp;a&nbsp;request&nbsp;parameter.<br> &nbsp;&nbsp;&nbsp;&nbsp;Currently&nbsp;only&nbsp;exclude=hashtags&nbsp;is&nbsp;supported.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;list&nbsp;with&nbsp;10&nbsp;entries.&nbsp;Each&nbsp;entry&nbsp;contains&nbsp;the&nbsp;twitter.</tt></dd></dl> <dl><dt><a name="Api-GetTrendsDaily"><strong>GetTrendsDaily</strong></a>(self, exclude<font color="#909090">=None</font>, startdate<font color="#909090">=None</font>)</dt><dd><tt>Get&nbsp;the&nbsp;current&nbsp;top&nbsp;trending&nbsp;topics&nbsp;for&nbsp;each&nbsp;hour&nbsp;in&nbsp;a&nbsp;given&nbsp;day<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;startdate:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;start&nbsp;date&nbsp;for&nbsp;the&nbsp;report.<br> &nbsp;&nbsp;&nbsp;&nbsp;Should&nbsp;be&nbsp;in&nbsp;the&nbsp;format&nbsp;YYYY-MM-DD.&nbsp;[Optional]<br> &nbsp;&nbsp;exclude:<br> &nbsp;&nbsp;&nbsp;&nbsp;Appends&nbsp;the&nbsp;exclude&nbsp;parameter&nbsp;as&nbsp;a&nbsp;request&nbsp;parameter.<br> &nbsp;&nbsp;&nbsp;&nbsp;Currently&nbsp;only&nbsp;exclude=hashtags&nbsp;is&nbsp;supported.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;list&nbsp;with&nbsp;24&nbsp;entries.&nbsp;Each&nbsp;entry&nbsp;contains&nbsp;the&nbsp;twitter.<br> &nbsp;&nbsp;<a href="#Trend">Trend</a>&nbsp;elements&nbsp;that&nbsp;were&nbsp;trending&nbsp;at&nbsp;the&nbsp;corresponding&nbsp;hour&nbsp;of&nbsp;the&nbsp;day.</tt></dd></dl> <dl><dt><a name="Api-GetTrendsWeekly"><strong>GetTrendsWeekly</strong></a>(self, exclude<font color="#909090">=None</font>, startdate<font color="#909090">=None</font>)</dt><dd><tt>Get&nbsp;the&nbsp;top&nbsp;30&nbsp;trending&nbsp;topics&nbsp;for&nbsp;each&nbsp;day&nbsp;in&nbsp;a&nbsp;given&nbsp;week.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;startdate:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;start&nbsp;date&nbsp;for&nbsp;the&nbsp;report.<br> &nbsp;&nbsp;&nbsp;&nbsp;Should&nbsp;be&nbsp;in&nbsp;the&nbsp;format&nbsp;YYYY-MM-DD.&nbsp;[Optional]<br> &nbsp;&nbsp;exclude:<br> &nbsp;&nbsp;&nbsp;&nbsp;Appends&nbsp;the&nbsp;exclude&nbsp;parameter&nbsp;as&nbsp;a&nbsp;request&nbsp;parameter.<br> &nbsp;&nbsp;&nbsp;&nbsp;Currently&nbsp;only&nbsp;exclude=hashtags&nbsp;is&nbsp;supported.&nbsp;[Optional]<br> Returns:<br> &nbsp;&nbsp;A&nbsp;list&nbsp;with&nbsp;each&nbsp;entry&nbsp;contains&nbsp;the&nbsp;twitter.<br> &nbsp;&nbsp;<a href="#Trend">Trend</a>&nbsp;elements&nbsp;of&nbsp;trending&nbsp;topics&nbsp;for&nbsp;the&nbsp;corrsponding&nbsp;day&nbsp;of&nbsp;the&nbsp;week</tt></dd></dl> <dl><dt><a name="Api-GetUser"><strong>GetUser</strong></a>(self, user)</dt><dd><tt>Returns&nbsp;a&nbsp;single&nbsp;user.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user:&nbsp;The&nbsp;twitter&nbsp;name&nbsp;or&nbsp;id&nbsp;of&nbsp;the&nbsp;user&nbsp;to&nbsp;retrieve.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#User">User</a>&nbsp;instance&nbsp;representing&nbsp;that&nbsp;user</tt></dd></dl> <dl><dt><a name="Api-GetUserByEmail"><strong>GetUserByEmail</strong></a>(self, email)</dt><dd><tt>Returns&nbsp;a&nbsp;single&nbsp;user&nbsp;by&nbsp;email&nbsp;address.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;email:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;email&nbsp;of&nbsp;the&nbsp;user&nbsp;to&nbsp;retrieve.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#User">User</a>&nbsp;instance&nbsp;representing&nbsp;that&nbsp;user</tt></dd></dl> <dl><dt><a name="Api-GetUserRetweets"><strong>GetUserRetweets</strong></a>(self, count<font color="#909090">=None</font>, since_id<font color="#909090">=None</font>, max_id<font color="#909090">=None</font>, include_entities<font color="#909090">=False</font>)</dt><dd><tt>Fetch&nbsp;the&nbsp;sequence&nbsp;of&nbsp;retweets&nbsp;made&nbsp;by&nbsp;a&nbsp;single&nbsp;user.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;count:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;number&nbsp;of&nbsp;status&nbsp;messages&nbsp;to&nbsp;retrieve.&nbsp;[Optional]<br> &nbsp;&nbsp;since_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Returns&nbsp;results&nbsp;with&nbsp;an&nbsp;ID&nbsp;greater&nbsp;than&nbsp;(that&nbsp;is,&nbsp;more&nbsp;recent<br> &nbsp;&nbsp;&nbsp;&nbsp;than)&nbsp;the&nbsp;specified&nbsp;ID.&nbsp;There&nbsp;are&nbsp;limits&nbsp;to&nbsp;the&nbsp;number&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;which&nbsp;can&nbsp;be&nbsp;accessed&nbsp;through&nbsp;the&nbsp;API.&nbsp;If&nbsp;the&nbsp;limit&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;has&nbsp;occured&nbsp;since&nbsp;the&nbsp;since_id,&nbsp;the&nbsp;since_id&nbsp;will&nbsp;be<br> &nbsp;&nbsp;&nbsp;&nbsp;forced&nbsp;to&nbsp;the&nbsp;oldest&nbsp;ID&nbsp;available.&nbsp;[Optional]<br> &nbsp;&nbsp;max_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Returns&nbsp;results&nbsp;with&nbsp;an&nbsp;ID&nbsp;less&nbsp;than&nbsp;(that&nbsp;is,&nbsp;older&nbsp;than)&nbsp;or<br> &nbsp;&nbsp;&nbsp;&nbsp;equal&nbsp;to&nbsp;the&nbsp;specified&nbsp;ID.&nbsp;[Optional]<br> &nbsp;&nbsp;include_entities:<br> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;True,&nbsp;each&nbsp;tweet&nbsp;will&nbsp;include&nbsp;a&nbsp;node&nbsp;called&nbsp;"entities,".<br> &nbsp;&nbsp;&nbsp;&nbsp;This&nbsp;node&nbsp;offers&nbsp;a&nbsp;variety&nbsp;of&nbsp;metadata&nbsp;about&nbsp;the&nbsp;tweet&nbsp;in&nbsp;a<br> &nbsp;&nbsp;&nbsp;&nbsp;discreet&nbsp;structure,&nbsp;including:&nbsp;user_mentions,&nbsp;urls,&nbsp;and<br> &nbsp;&nbsp;&nbsp;&nbsp;hashtags.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;message&nbsp;up&nbsp;to&nbsp;count</tt></dd></dl> <dl><dt><a name="Api-GetUserTimeline"><strong>GetUserTimeline</strong></a>(self, id<font color="#909090">=None</font>, user_id<font color="#909090">=None</font>, screen_name<font color="#909090">=None</font>, since_id<font color="#909090">=None</font>, max_id<font color="#909090">=None</font>, count<font color="#909090">=None</font>, page<font color="#909090">=None</font>, include_rts<font color="#909090">=None</font>, include_entities<font color="#909090">=None</font>)</dt><dd><tt>Fetch&nbsp;the&nbsp;sequence&nbsp;of&nbsp;public&nbsp;<a href="#Status">Status</a>&nbsp;messages&nbsp;for&nbsp;a&nbsp;single&nbsp;user.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated&nbsp;if&nbsp;the&nbsp;user&nbsp;is&nbsp;private.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Specifies&nbsp;the&nbsp;ID&nbsp;or&nbsp;screen&nbsp;name&nbsp;of&nbsp;the&nbsp;user&nbsp;for&nbsp;whom&nbsp;to&nbsp;return<br> &nbsp;&nbsp;&nbsp;&nbsp;the&nbsp;user_timeline.&nbsp;[Optional]<br> &nbsp;&nbsp;user_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Specfies&nbsp;the&nbsp;ID&nbsp;of&nbsp;the&nbsp;user&nbsp;for&nbsp;whom&nbsp;to&nbsp;return&nbsp;the<br> &nbsp;&nbsp;&nbsp;&nbsp;user_timeline.&nbsp;Helpful&nbsp;for&nbsp;disambiguating&nbsp;when&nbsp;a&nbsp;valid&nbsp;user&nbsp;ID<br> &nbsp;&nbsp;&nbsp;&nbsp;is&nbsp;also&nbsp;a&nbsp;valid&nbsp;screen&nbsp;name.&nbsp;[Optional]<br> &nbsp;&nbsp;screen_name:<br> &nbsp;&nbsp;&nbsp;&nbsp;Specfies&nbsp;the&nbsp;screen&nbsp;name&nbsp;of&nbsp;the&nbsp;user&nbsp;for&nbsp;whom&nbsp;to&nbsp;return&nbsp;the<br> &nbsp;&nbsp;&nbsp;&nbsp;user_timeline.&nbsp;Helpful&nbsp;for&nbsp;disambiguating&nbsp;when&nbsp;a&nbsp;valid&nbsp;screen<br> &nbsp;&nbsp;&nbsp;&nbsp;name&nbsp;is&nbsp;also&nbsp;a&nbsp;user&nbsp;ID.&nbsp;[Optional]<br> &nbsp;&nbsp;since_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Returns&nbsp;results&nbsp;with&nbsp;an&nbsp;ID&nbsp;greater&nbsp;than&nbsp;(that&nbsp;is,&nbsp;more&nbsp;recent<br> &nbsp;&nbsp;&nbsp;&nbsp;than)&nbsp;the&nbsp;specified&nbsp;ID.&nbsp;There&nbsp;are&nbsp;limits&nbsp;to&nbsp;the&nbsp;number&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;which&nbsp;can&nbsp;be&nbsp;accessed&nbsp;through&nbsp;the&nbsp;API.&nbsp;If&nbsp;the&nbsp;limit&nbsp;of<br> &nbsp;&nbsp;&nbsp;&nbsp;Tweets&nbsp;has&nbsp;occured&nbsp;since&nbsp;the&nbsp;since_id,&nbsp;the&nbsp;since_id&nbsp;will&nbsp;be<br> &nbsp;&nbsp;&nbsp;&nbsp;forced&nbsp;to&nbsp;the&nbsp;oldest&nbsp;ID&nbsp;available.&nbsp;[Optional]<br> &nbsp;&nbsp;max_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;Returns&nbsp;only&nbsp;statuses&nbsp;with&nbsp;an&nbsp;ID&nbsp;less&nbsp;than&nbsp;(that&nbsp;is,&nbsp;older<br> &nbsp;&nbsp;&nbsp;&nbsp;than)&nbsp;or&nbsp;equal&nbsp;to&nbsp;the&nbsp;specified&nbsp;ID.&nbsp;[Optional]<br> &nbsp;&nbsp;count:<br> &nbsp;&nbsp;&nbsp;&nbsp;Specifies&nbsp;the&nbsp;number&nbsp;of&nbsp;statuses&nbsp;to&nbsp;retrieve.&nbsp;May&nbsp;not&nbsp;be<br> &nbsp;&nbsp;&nbsp;&nbsp;greater&nbsp;than&nbsp;200.&nbsp;&nbsp;[Optional]<br> &nbsp;&nbsp;page:<br> &nbsp;&nbsp;&nbsp;&nbsp;Specifies&nbsp;the&nbsp;page&nbsp;of&nbsp;results&nbsp;to&nbsp;retrieve.<br> &nbsp;&nbsp;&nbsp;&nbsp;Note:&nbsp;there&nbsp;are&nbsp;pagination&nbsp;limits.&nbsp;[Optional]<br> &nbsp;&nbsp;include_rts:<br> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;True,&nbsp;the&nbsp;timeline&nbsp;will&nbsp;contain&nbsp;native&nbsp;retweets&nbsp;(if&nbsp;they<br> &nbsp;&nbsp;&nbsp;&nbsp;exist)&nbsp;in&nbsp;addition&nbsp;to&nbsp;the&nbsp;standard&nbsp;stream&nbsp;of&nbsp;tweets.&nbsp;[Optional]<br> &nbsp;&nbsp;include_entities:<br> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;True,&nbsp;each&nbsp;tweet&nbsp;will&nbsp;include&nbsp;a&nbsp;node&nbsp;called&nbsp;"entities,".<br> &nbsp;&nbsp;&nbsp;&nbsp;This&nbsp;node&nbsp;offers&nbsp;a&nbsp;variety&nbsp;of&nbsp;metadata&nbsp;about&nbsp;the&nbsp;tweet&nbsp;in&nbsp;a<br> &nbsp;&nbsp;&nbsp;&nbsp;discreet&nbsp;structure,&nbsp;including:&nbsp;user_mentions,&nbsp;urls,&nbsp;and<br> &nbsp;&nbsp;&nbsp;&nbsp;hashtags.&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;sequence&nbsp;of&nbsp;<a href="#Status">Status</a>&nbsp;instances,&nbsp;one&nbsp;for&nbsp;each&nbsp;message&nbsp;up&nbsp;to&nbsp;count</tt></dd></dl> <dl><dt><a name="Api-MaximumHitFrequency"><strong>MaximumHitFrequency</strong></a>(self)</dt><dd><tt>Determines&nbsp;the&nbsp;minimum&nbsp;number&nbsp;of&nbsp;seconds&nbsp;that&nbsp;a&nbsp;program&nbsp;must&nbsp;wait<br> before&nbsp;hitting&nbsp;the&nbsp;server&nbsp;again&nbsp;without&nbsp;exceeding&nbsp;the&nbsp;rate_limit<br> imposed&nbsp;for&nbsp;the&nbsp;currently&nbsp;authenticated&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;minimum&nbsp;second&nbsp;interval&nbsp;that&nbsp;a&nbsp;program&nbsp;must&nbsp;use&nbsp;so&nbsp;as&nbsp;to&nbsp;not<br> &nbsp;&nbsp;exceed&nbsp;the&nbsp;rate_limit&nbsp;imposed&nbsp;for&nbsp;the&nbsp;user.</tt></dd></dl> <dl><dt><a name="Api-PostDirectMessage"><strong>PostDirectMessage</strong></a>(self, user, text)</dt><dd><tt>Post&nbsp;a&nbsp;twitter&nbsp;direct&nbsp;message&nbsp;from&nbsp;the&nbsp;authenticated&nbsp;user<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user:&nbsp;The&nbsp;ID&nbsp;or&nbsp;screen&nbsp;name&nbsp;of&nbsp;the&nbsp;recipient&nbsp;user.<br> &nbsp;&nbsp;text:&nbsp;The&nbsp;message&nbsp;text&nbsp;to&nbsp;be&nbsp;posted.&nbsp;&nbsp;Must&nbsp;be&nbsp;less&nbsp;than&nbsp;140&nbsp;characters.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#DirectMessage">DirectMessage</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;message&nbsp;posted</tt></dd></dl> <dl><dt><a name="Api-PostUpdate"><strong>PostUpdate</strong></a>(self, status, in_reply_to_status_id<font color="#909090">=None</font>)</dt><dd><tt>Post&nbsp;a&nbsp;twitter&nbsp;status&nbsp;message&nbsp;from&nbsp;the&nbsp;authenticated&nbsp;user.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;status:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;message&nbsp;text&nbsp;to&nbsp;be&nbsp;posted.<br> &nbsp;&nbsp;&nbsp;&nbsp;Must&nbsp;be&nbsp;less&nbsp;than&nbsp;or&nbsp;equal&nbsp;to&nbsp;140&nbsp;characters.<br> &nbsp;&nbsp;in_reply_to_status_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;ID&nbsp;of&nbsp;an&nbsp;existing&nbsp;status&nbsp;that&nbsp;the&nbsp;status&nbsp;to&nbsp;be&nbsp;posted&nbsp;is<br> &nbsp;&nbsp;&nbsp;&nbsp;in&nbsp;reply&nbsp;to.&nbsp;&nbsp;This&nbsp;implicitly&nbsp;sets&nbsp;the&nbsp;in_reply_to_user_id<br> &nbsp;&nbsp;&nbsp;&nbsp;attribute&nbsp;of&nbsp;the&nbsp;resulting&nbsp;status&nbsp;to&nbsp;the&nbsp;user&nbsp;ID&nbsp;of&nbsp;the<br> &nbsp;&nbsp;&nbsp;&nbsp;message&nbsp;being&nbsp;replied&nbsp;to.&nbsp;&nbsp;Invalid/missing&nbsp;status&nbsp;IDs&nbsp;will&nbsp;be<br> &nbsp;&nbsp;&nbsp;&nbsp;ignored.&nbsp;[Optional]<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;message&nbsp;posted.</tt></dd></dl> <dl><dt><a name="Api-PostUpdates"><strong>PostUpdates</strong></a>(self, status, continuation<font color="#909090">=None</font>, **kwargs)</dt><dd><tt>Post&nbsp;one&nbsp;or&nbsp;more&nbsp;twitter&nbsp;status&nbsp;messages&nbsp;from&nbsp;the&nbsp;authenticated&nbsp;user.<br> &nbsp;<br> Unlike&nbsp;api.PostUpdate,&nbsp;this&nbsp;method&nbsp;will&nbsp;post&nbsp;multiple&nbsp;status&nbsp;updates<br> if&nbsp;the&nbsp;message&nbsp;is&nbsp;longer&nbsp;than&nbsp;140&nbsp;characters.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;status:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;message&nbsp;text&nbsp;to&nbsp;be&nbsp;posted.<br> &nbsp;&nbsp;&nbsp;&nbsp;May&nbsp;be&nbsp;longer&nbsp;than&nbsp;140&nbsp;characters.<br> &nbsp;&nbsp;continuation:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;character&nbsp;string,&nbsp;if&nbsp;any,&nbsp;to&nbsp;be&nbsp;appended&nbsp;to&nbsp;all&nbsp;but&nbsp;the<br> &nbsp;&nbsp;&nbsp;&nbsp;last&nbsp;message.&nbsp;&nbsp;Note&nbsp;that&nbsp;Twitter&nbsp;strips&nbsp;trailing&nbsp;'...'&nbsp;strings<br> &nbsp;&nbsp;&nbsp;&nbsp;from&nbsp;messages.&nbsp;&nbsp;Consider&nbsp;using&nbsp;the&nbsp;unicode&nbsp;\u2026&nbsp;character<br> &nbsp;&nbsp;&nbsp;&nbsp;(horizontal&nbsp;ellipsis)&nbsp;instead.&nbsp;[Defaults&nbsp;to&nbsp;None]<br> &nbsp;&nbsp;**kwargs:<br> &nbsp;&nbsp;&nbsp;&nbsp;See&nbsp;api.PostUpdate&nbsp;for&nbsp;a&nbsp;list&nbsp;of&nbsp;accepted&nbsp;parameters.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;of&nbsp;list&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;messages&nbsp;posted.</tt></dd></dl> <dl><dt><a name="Api-SetCache"><strong>SetCache</strong></a>(self, cache)</dt><dd><tt>Override&nbsp;the&nbsp;default&nbsp;cache.&nbsp;&nbsp;Set&nbsp;to&nbsp;None&nbsp;to&nbsp;prevent&nbsp;caching.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;cache:<br> &nbsp;&nbsp;&nbsp;&nbsp;An&nbsp;instance&nbsp;that&nbsp;supports&nbsp;the&nbsp;same&nbsp;API&nbsp;as&nbsp;the&nbsp;twitter._FileCache</tt></dd></dl> <dl><dt><a name="Api-SetCacheTimeout"><strong>SetCacheTimeout</strong></a>(self, cache_timeout)</dt><dd><tt>Override&nbsp;the&nbsp;default&nbsp;cache&nbsp;timeout.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;cache_timeout:<br> &nbsp;&nbsp;&nbsp;&nbsp;Time,&nbsp;in&nbsp;seconds,&nbsp;that&nbsp;responses&nbsp;should&nbsp;be&nbsp;reused.</tt></dd></dl> <dl><dt><a name="Api-SetCredentials"><strong>SetCredentials</strong></a>(self, consumer_key, consumer_secret, access_token_key<font color="#909090">=None</font>, access_token_secret<font color="#909090">=None</font>)</dt><dd><tt>Set&nbsp;the&nbsp;consumer_key&nbsp;and&nbsp;consumer_secret&nbsp;for&nbsp;this&nbsp;instance<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;consumer_key:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;consumer_key&nbsp;of&nbsp;the&nbsp;twitter&nbsp;account.<br> &nbsp;&nbsp;consumer_secret:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;consumer_secret&nbsp;for&nbsp;the&nbsp;twitter&nbsp;account.<br> &nbsp;&nbsp;access_token_key:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;oAuth&nbsp;access&nbsp;token&nbsp;key&nbsp;value&nbsp;you&nbsp;retrieved<br> &nbsp;&nbsp;&nbsp;&nbsp;from&nbsp;running&nbsp;get_access_token.py.<br> &nbsp;&nbsp;access_token_secret:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;oAuth&nbsp;access&nbsp;token's&nbsp;secret,&nbsp;also&nbsp;retrieved<br> &nbsp;&nbsp;&nbsp;&nbsp;from&nbsp;the&nbsp;get_access_token.py&nbsp;run.</tt></dd></dl> <dl><dt><a name="Api-SetSource"><strong>SetSource</strong></a>(self, source)</dt><dd><tt>Suggest&nbsp;the&nbsp;"from&nbsp;source"&nbsp;value&nbsp;to&nbsp;be&nbsp;displayed&nbsp;on&nbsp;the&nbsp;Twitter&nbsp;web&nbsp;site.<br> &nbsp;<br> The&nbsp;value&nbsp;of&nbsp;the&nbsp;'source'&nbsp;parameter&nbsp;must&nbsp;be&nbsp;first&nbsp;recognized&nbsp;by<br> the&nbsp;Twitter&nbsp;server.&nbsp;&nbsp;New&nbsp;source&nbsp;values&nbsp;are&nbsp;authorized&nbsp;on&nbsp;a&nbsp;case&nbsp;by<br> case&nbsp;basis&nbsp;by&nbsp;the&nbsp;Twitter&nbsp;development&nbsp;team.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;source:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;source&nbsp;name&nbsp;as&nbsp;a&nbsp;string.&nbsp;&nbsp;Will&nbsp;be&nbsp;sent&nbsp;to&nbsp;the&nbsp;server&nbsp;as<br> &nbsp;&nbsp;&nbsp;&nbsp;the&nbsp;'source'&nbsp;parameter.</tt></dd></dl> <dl><dt><a name="Api-SetUrllib"><strong>SetUrllib</strong></a>(self, urllib)</dt><dd><tt>Override&nbsp;the&nbsp;default&nbsp;urllib&nbsp;implementation.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;urllib:<br> &nbsp;&nbsp;&nbsp;&nbsp;An&nbsp;instance&nbsp;that&nbsp;supports&nbsp;the&nbsp;same&nbsp;API&nbsp;as&nbsp;the&nbsp;urllib2&nbsp;module</tt></dd></dl> <dl><dt><a name="Api-SetUserAgent"><strong>SetUserAgent</strong></a>(self, user_agent)</dt><dd><tt>Override&nbsp;the&nbsp;default&nbsp;user&nbsp;agent<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user_agent:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;string&nbsp;that&nbsp;should&nbsp;be&nbsp;send&nbsp;to&nbsp;the&nbsp;server&nbsp;as&nbsp;the&nbsp;<a href="#User">User</a>-agent</tt></dd></dl> <dl><dt><a name="Api-SetXTwitterHeaders"><strong>SetXTwitterHeaders</strong></a>(self, client, url, version)</dt><dd><tt>Set&nbsp;the&nbsp;X-Twitter&nbsp;HTTP&nbsp;headers&nbsp;that&nbsp;will&nbsp;be&nbsp;sent&nbsp;to&nbsp;the&nbsp;server.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;client:<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;client&nbsp;name&nbsp;as&nbsp;a&nbsp;string.&nbsp;&nbsp;Will&nbsp;be&nbsp;sent&nbsp;to&nbsp;the&nbsp;server&nbsp;as<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;the&nbsp;'X-Twitter-Client'&nbsp;header.<br> &nbsp;&nbsp;url:<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;URL&nbsp;of&nbsp;the&nbsp;meta.xml&nbsp;as&nbsp;a&nbsp;string.&nbsp;&nbsp;Will&nbsp;be&nbsp;sent&nbsp;to&nbsp;the&nbsp;server<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;as&nbsp;the&nbsp;'X-Twitter-Client-URL'&nbsp;header.<br> &nbsp;&nbsp;version:<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;client&nbsp;version&nbsp;as&nbsp;a&nbsp;string.&nbsp;&nbsp;Will&nbsp;be&nbsp;sent&nbsp;to&nbsp;the&nbsp;server<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;as&nbsp;the&nbsp;'X-Twitter-Client-Version'&nbsp;header.</tt></dd></dl> <dl><dt><a name="Api-UsersLookup"><strong>UsersLookup</strong></a>(self, user_id<font color="#909090">=None</font>, screen_name<font color="#909090">=None</font>, users<font color="#909090">=None</font>)</dt><dd><tt>Fetch&nbsp;extended&nbsp;information&nbsp;for&nbsp;the&nbsp;specified&nbsp;users.<br> &nbsp;<br> Users&nbsp;may&nbsp;be&nbsp;specified&nbsp;either&nbsp;as&nbsp;lists&nbsp;of&nbsp;either&nbsp;user_ids,<br> screen_names,&nbsp;or&nbsp;twitter.<a href="#User">User</a>&nbsp;objects.&nbsp;The&nbsp;list&nbsp;of&nbsp;users&nbsp;that<br> are&nbsp;queried&nbsp;is&nbsp;the&nbsp;union&nbsp;of&nbsp;all&nbsp;specified&nbsp;parameters.<br> &nbsp;<br> The&nbsp;twitter.<a href="#Api">Api</a>&nbsp;instance&nbsp;must&nbsp;be&nbsp;authenticated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;list&nbsp;of&nbsp;user_ids&nbsp;to&nbsp;retrieve&nbsp;extended&nbsp;information.<br> &nbsp;&nbsp;&nbsp;&nbsp;[Optional]<br> &nbsp;&nbsp;screen_name:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;list&nbsp;of&nbsp;screen_names&nbsp;to&nbsp;retrieve&nbsp;extended&nbsp;information.<br> &nbsp;&nbsp;&nbsp;&nbsp;[Optional]<br> &nbsp;&nbsp;users:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;list&nbsp;of&nbsp;twitter.<a href="#User">User</a>&nbsp;objects&nbsp;to&nbsp;retrieve&nbsp;extended&nbsp;information.<br> &nbsp;&nbsp;&nbsp;&nbsp;[Optional]<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;list&nbsp;of&nbsp;twitter.<a href="#User">User</a>&nbsp;objects&nbsp;for&nbsp;the&nbsp;requested&nbsp;users</tt></dd></dl> <dl><dt><a name="Api-VerifyCredentials"><strong>VerifyCredentials</strong></a>(self)</dt><dd><tt>Returns&nbsp;a&nbsp;twitter.<a href="#User">User</a>&nbsp;instance&nbsp;if&nbsp;the&nbsp;authenticating&nbsp;user&nbsp;is&nbsp;valid.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#User">User</a>&nbsp;instance&nbsp;representing&nbsp;that&nbsp;user&nbsp;if&nbsp;the<br> &nbsp;&nbsp;credentials&nbsp;are&nbsp;valid,&nbsp;None&nbsp;otherwise.</tt></dd></dl> <dl><dt><a name="Api-__init__"><strong>__init__</strong></a>(self, consumer_key<font color="#909090">=None</font>, consumer_secret<font color="#909090">=None</font>, access_token_key<font color="#909090">=None</font>, access_token_secret<font color="#909090">=None</font>, input_encoding<font color="#909090">=None</font>, request_headers<font color="#909090">=None</font>, cache<font color="#909090">=&lt;object object at 0x1001da0a0&gt;</font>, shortner<font color="#909090">=None</font>, base_url<font color="#909090">=None</font>, use_gzip_compression<font color="#909090">=False</font>, debugHTTP<font color="#909090">=False</font>)</dt><dd><tt>Instantiate&nbsp;a&nbsp;new&nbsp;twitter.<a href="#Api">Api</a>&nbsp;<a href="__builtin__.html#object">object</a>.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;consumer_key:<br> &nbsp;&nbsp;&nbsp;&nbsp;Your&nbsp;Twitter&nbsp;user's&nbsp;consumer_key.<br> &nbsp;&nbsp;consumer_secret:<br> &nbsp;&nbsp;&nbsp;&nbsp;Your&nbsp;Twitter&nbsp;user's&nbsp;consumer_secret.<br> &nbsp;&nbsp;access_token_key:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;oAuth&nbsp;access&nbsp;token&nbsp;key&nbsp;value&nbsp;you&nbsp;retrieved<br> &nbsp;&nbsp;&nbsp;&nbsp;from&nbsp;running&nbsp;get_access_token.py.<br> &nbsp;&nbsp;access_token_secret:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;oAuth&nbsp;access&nbsp;token's&nbsp;secret,&nbsp;also&nbsp;retrieved<br> &nbsp;&nbsp;&nbsp;&nbsp;from&nbsp;the&nbsp;get_access_token.py&nbsp;run.<br> &nbsp;&nbsp;input_encoding:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;encoding&nbsp;used&nbsp;to&nbsp;encode&nbsp;input&nbsp;strings.&nbsp;[Optional]<br> &nbsp;&nbsp;request_header:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;dictionary&nbsp;of&nbsp;additional&nbsp;HTTP&nbsp;request&nbsp;headers.&nbsp;[Optional]<br> &nbsp;&nbsp;cache:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;cache&nbsp;instance&nbsp;to&nbsp;use.&nbsp;Defaults&nbsp;to&nbsp;DEFAULT_CACHE.<br> &nbsp;&nbsp;&nbsp;&nbsp;Use&nbsp;None&nbsp;to&nbsp;disable&nbsp;caching.&nbsp;[Optional]<br> &nbsp;&nbsp;shortner:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;shortner&nbsp;instance&nbsp;to&nbsp;use.&nbsp;&nbsp;Defaults&nbsp;to&nbsp;None.<br> &nbsp;&nbsp;&nbsp;&nbsp;See&nbsp;shorten_url.py&nbsp;for&nbsp;an&nbsp;example&nbsp;shortner.&nbsp;[Optional]<br> &nbsp;&nbsp;base_url:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;base&nbsp;URL&nbsp;to&nbsp;use&nbsp;to&nbsp;contact&nbsp;the&nbsp;Twitter&nbsp;API.<br> &nbsp;&nbsp;&nbsp;&nbsp;Defaults&nbsp;to&nbsp;https://twitter.com.&nbsp;[Optional]<br> &nbsp;&nbsp;use_gzip_compression:<br> &nbsp;&nbsp;&nbsp;&nbsp;Set&nbsp;to&nbsp;True&nbsp;to&nbsp;tell&nbsp;enable&nbsp;gzip&nbsp;compression&nbsp;for&nbsp;any&nbsp;call<br> &nbsp;&nbsp;&nbsp;&nbsp;made&nbsp;to&nbsp;Twitter.&nbsp;&nbsp;Defaults&nbsp;to&nbsp;False.&nbsp;[Optional]<br> &nbsp;&nbsp;debugHTTP:<br> &nbsp;&nbsp;&nbsp;&nbsp;Set&nbsp;to&nbsp;True&nbsp;to&nbsp;enable&nbsp;debug&nbsp;output&nbsp;from&nbsp;urllib2&nbsp;when&nbsp;performing<br> &nbsp;&nbsp;&nbsp;&nbsp;any&nbsp;HTTP&nbsp;requests.&nbsp;&nbsp;Defaults&nbsp;to&nbsp;False.&nbsp;[Optional]</tt></dd></dl> <hr> Data descriptors defined here:<br> <dl><dt><strong>__dict__</strong></dt> <dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>__weakref__</strong></dt> <dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd> </dl> <hr> Data and other attributes defined here:<br> <dl><dt><strong>DEFAULT_CACHE_TIMEOUT</strong> = 60</dl> </td></tr></table> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="DirectMessage">class <strong>DirectMessage</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr> <tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td> <td colspan=2><tt>A&nbsp;class&nbsp;representing&nbsp;the&nbsp;<a href="#DirectMessage">DirectMessage</a>&nbsp;structure&nbsp;used&nbsp;by&nbsp;the&nbsp;twitter&nbsp;API.<br> &nbsp;<br> The&nbsp;<a href="#DirectMessage">DirectMessage</a>&nbsp;structure&nbsp;exposes&nbsp;the&nbsp;following&nbsp;properties:<br> &nbsp;<br> &nbsp;&nbsp;direct_message.id<br> &nbsp;&nbsp;direct_message.created_at<br> &nbsp;&nbsp;direct_message.created_at_in_seconds&nbsp;#&nbsp;read&nbsp;only<br> &nbsp;&nbsp;direct_message.sender_id<br> &nbsp;&nbsp;direct_message.sender_screen_name<br> &nbsp;&nbsp;direct_message.recipient_id<br> &nbsp;&nbsp;direct_message.recipient_screen_name<br> &nbsp;&nbsp;direct_message.text<br>&nbsp;</tt></td></tr> <tr><td>&nbsp;</td> <td width="100%">Methods defined here:<br> <dl><dt><a name="DirectMessage-AsDict"><strong>AsDict</strong></a>(self)</dt><dd><tt>A&nbsp;dict&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#DirectMessage">DirectMessage</a>&nbsp;instance.<br> &nbsp;<br> The&nbsp;return&nbsp;value&nbsp;uses&nbsp;the&nbsp;same&nbsp;key&nbsp;names&nbsp;as&nbsp;the&nbsp;JSON&nbsp;representation.<br> &nbsp;<br> Return:<br> &nbsp;&nbsp;A&nbsp;dict&nbsp;representing&nbsp;this&nbsp;twitter.<a href="#DirectMessage">DirectMessage</a>&nbsp;instance</tt></dd></dl> <dl><dt><a name="DirectMessage-AsJsonString"><strong>AsJsonString</strong></a>(self)</dt><dd><tt>A&nbsp;JSON&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#DirectMessage">DirectMessage</a>&nbsp;instance.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;JSON&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#DirectMessage">DirectMessage</a>&nbsp;instance</tt></dd></dl> <dl><dt><a name="DirectMessage-GetCreatedAt"><strong>GetCreatedAt</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;time&nbsp;this&nbsp;direct&nbsp;message&nbsp;was&nbsp;posted.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;time&nbsp;this&nbsp;direct&nbsp;message&nbsp;was&nbsp;posted</tt></dd></dl> <dl><dt><a name="DirectMessage-GetCreatedAtInSeconds"><strong>GetCreatedAtInSeconds</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;time&nbsp;this&nbsp;direct&nbsp;message&nbsp;was&nbsp;posted,&nbsp;in&nbsp;seconds&nbsp;since&nbsp;the&nbsp;epoch.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;time&nbsp;this&nbsp;direct&nbsp;message&nbsp;was&nbsp;posted,&nbsp;in&nbsp;seconds&nbsp;since&nbsp;the&nbsp;epoch.</tt></dd></dl> <dl><dt><a name="DirectMessage-GetId"><strong>GetId</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message</tt></dd></dl> <dl><dt><a name="DirectMessage-GetRecipientId"><strong>GetRecipientId</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;unique&nbsp;recipient&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;unique&nbsp;recipient&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message</tt></dd></dl> <dl><dt><a name="DirectMessage-GetRecipientScreenName"><strong>GetRecipientScreenName</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;unique&nbsp;recipient&nbsp;screen&nbsp;name&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;unique&nbsp;recipient&nbsp;screen&nbsp;name&nbsp;of&nbsp;this&nbsp;direct&nbsp;message</tt></dd></dl> <dl><dt><a name="DirectMessage-GetSenderId"><strong>GetSenderId</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;unique&nbsp;sender&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;unique&nbsp;sender&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message</tt></dd></dl> <dl><dt><a name="DirectMessage-GetSenderScreenName"><strong>GetSenderScreenName</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;unique&nbsp;sender&nbsp;screen&nbsp;name&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;unique&nbsp;sender&nbsp;screen&nbsp;name&nbsp;of&nbsp;this&nbsp;direct&nbsp;message</tt></dd></dl> <dl><dt><a name="DirectMessage-GetText"><strong>GetText</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;text&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;text&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.</tt></dd></dl> <dl><dt><a name="DirectMessage-SetCreatedAt"><strong>SetCreatedAt</strong></a>(self, created_at)</dt><dd><tt>Set&nbsp;the&nbsp;time&nbsp;this&nbsp;direct&nbsp;message&nbsp;was&nbsp;posted.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;created_at:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;time&nbsp;this&nbsp;direct&nbsp;message&nbsp;was&nbsp;created</tt></dd></dl> <dl><dt><a name="DirectMessage-SetId"><strong>SetId</strong></a>(self, id)</dt><dd><tt>Set&nbsp;the&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;id:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message</tt></dd></dl> <dl><dt><a name="DirectMessage-SetRecipientId"><strong>SetRecipientId</strong></a>(self, recipient_id)</dt><dd><tt>Set&nbsp;the&nbsp;unique&nbsp;recipient&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;recipient_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;unique&nbsp;recipient&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message</tt></dd></dl> <dl><dt><a name="DirectMessage-SetRecipientScreenName"><strong>SetRecipientScreenName</strong></a>(self, recipient_screen_name)</dt><dd><tt>Set&nbsp;the&nbsp;unique&nbsp;recipient&nbsp;screen&nbsp;name&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;recipient_screen_name:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;unique&nbsp;recipient&nbsp;screen&nbsp;name&nbsp;of&nbsp;this&nbsp;direct&nbsp;message</tt></dd></dl> <dl><dt><a name="DirectMessage-SetSenderId"><strong>SetSenderId</strong></a>(self, sender_id)</dt><dd><tt>Set&nbsp;the&nbsp;unique&nbsp;sender&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;sender_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;unique&nbsp;sender&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message</tt></dd></dl> <dl><dt><a name="DirectMessage-SetSenderScreenName"><strong>SetSenderScreenName</strong></a>(self, sender_screen_name)</dt><dd><tt>Set&nbsp;the&nbsp;unique&nbsp;sender&nbsp;screen&nbsp;name&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;sender_screen_name:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;unique&nbsp;sender&nbsp;screen&nbsp;name&nbsp;of&nbsp;this&nbsp;direct&nbsp;message</tt></dd></dl> <dl><dt><a name="DirectMessage-SetText"><strong>SetText</strong></a>(self, text)</dt><dd><tt>Set&nbsp;the&nbsp;text&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;text:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;text&nbsp;of&nbsp;this&nbsp;direct&nbsp;message</tt></dd></dl> <dl><dt><a name="DirectMessage-__eq__"><strong>__eq__</strong></a>(self, other)</dt></dl> <dl><dt><a name="DirectMessage-__init__"><strong>__init__</strong></a>(self, id<font color="#909090">=None</font>, created_at<font color="#909090">=None</font>, sender_id<font color="#909090">=None</font>, sender_screen_name<font color="#909090">=None</font>, recipient_id<font color="#909090">=None</font>, recipient_screen_name<font color="#909090">=None</font>, text<font color="#909090">=None</font>)</dt><dd><tt>An&nbsp;<a href="__builtin__.html#object">object</a>&nbsp;to&nbsp;hold&nbsp;a&nbsp;Twitter&nbsp;direct&nbsp;message.<br> &nbsp;<br> This&nbsp;class&nbsp;is&nbsp;normally&nbsp;instantiated&nbsp;by&nbsp;the&nbsp;twitter.<a href="#Api">Api</a>&nbsp;class&nbsp;and<br> returned&nbsp;in&nbsp;a&nbsp;sequence.<br> &nbsp;<br> Note:&nbsp;Dates&nbsp;are&nbsp;posted&nbsp;in&nbsp;the&nbsp;form&nbsp;"Sat&nbsp;Jan&nbsp;27&nbsp;04:17:38&nbsp;+0000&nbsp;2007"<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;id:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.&nbsp;[Optional]<br> &nbsp;&nbsp;created_at:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;time&nbsp;this&nbsp;direct&nbsp;message&nbsp;was&nbsp;posted.&nbsp;[Optional]<br> &nbsp;&nbsp;sender_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;id&nbsp;of&nbsp;the&nbsp;twitter&nbsp;user&nbsp;that&nbsp;sent&nbsp;this&nbsp;message.&nbsp;[Optional]<br> &nbsp;&nbsp;sender_screen_name:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;name&nbsp;of&nbsp;the&nbsp;twitter&nbsp;user&nbsp;that&nbsp;sent&nbsp;this&nbsp;message.&nbsp;[Optional]<br> &nbsp;&nbsp;recipient_id:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;id&nbsp;of&nbsp;the&nbsp;twitter&nbsp;that&nbsp;received&nbsp;this&nbsp;message.&nbsp;[Optional]<br> &nbsp;&nbsp;recipient_screen_name:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;name&nbsp;of&nbsp;the&nbsp;twitter&nbsp;that&nbsp;received&nbsp;this&nbsp;message.&nbsp;[Optional]<br> &nbsp;&nbsp;text:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;text&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.&nbsp;[Optional]</tt></dd></dl> <dl><dt><a name="DirectMessage-__ne__"><strong>__ne__</strong></a>(self, other)</dt></dl> <dl><dt><a name="DirectMessage-__str__"><strong>__str__</strong></a>(self)</dt><dd><tt>A&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#DirectMessage">DirectMessage</a>&nbsp;instance.<br> &nbsp;<br> The&nbsp;return&nbsp;value&nbsp;is&nbsp;the&nbsp;same&nbsp;as&nbsp;the&nbsp;JSON&nbsp;string&nbsp;representation.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#DirectMessage">DirectMessage</a>&nbsp;instance.</tt></dd></dl> <hr> Static methods defined here:<br> <dl><dt><a name="DirectMessage-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data)</dt><dd><tt>Create&nbsp;a&nbsp;new&nbsp;instance&nbsp;based&nbsp;on&nbsp;a&nbsp;JSON&nbsp;dict.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;data:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;JSON&nbsp;dict,&nbsp;as&nbsp;converted&nbsp;from&nbsp;the&nbsp;JSON&nbsp;in&nbsp;the&nbsp;twitter&nbsp;API<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#DirectMessage">DirectMessage</a>&nbsp;instance</tt></dd></dl> <hr> Data descriptors defined here:<br> <dl><dt><strong>__dict__</strong></dt> <dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>__weakref__</strong></dt> <dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>created_at</strong></dt> <dd><tt>The&nbsp;time&nbsp;this&nbsp;direct&nbsp;message&nbsp;was&nbsp;posted.</tt></dd> </dl> <dl><dt><strong>created_at_in_seconds</strong></dt> <dd><tt>The&nbsp;time&nbsp;this&nbsp;direct&nbsp;message&nbsp;was&nbsp;posted,&nbsp;in&nbsp;seconds&nbsp;since&nbsp;the&nbsp;epoch</tt></dd> </dl> <dl><dt><strong>id</strong></dt> <dd><tt>The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.</tt></dd> </dl> <dl><dt><strong>recipient_id</strong></dt> <dd><tt>The&nbsp;unique&nbsp;recipient&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.</tt></dd> </dl> <dl><dt><strong>recipient_screen_name</strong></dt> <dd><tt>The&nbsp;unique&nbsp;recipient&nbsp;screen&nbsp;name&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.</tt></dd> </dl> <dl><dt><strong>sender_id</strong></dt> <dd><tt>The&nbsp;unique&nbsp;sender&nbsp;id&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.</tt></dd> </dl> <dl><dt><strong>sender_screen_name</strong></dt> <dd><tt>The&nbsp;unique&nbsp;sender&nbsp;screen&nbsp;name&nbsp;of&nbsp;this&nbsp;direct&nbsp;message.</tt></dd> </dl> <dl><dt><strong>text</strong></dt> <dd><tt>The&nbsp;text&nbsp;of&nbsp;this&nbsp;direct&nbsp;message</tt></dd> </dl> </td></tr></table> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="Hashtag">class <strong>Hashtag</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr> <tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td> <td colspan=2><tt>A&nbsp;class&nbsp;represeinting&nbsp;a&nbsp;twitter&nbsp;hashtag<br>&nbsp;</tt></td></tr> <tr><td>&nbsp;</td> <td width="100%">Methods defined here:<br> <dl><dt><a name="Hashtag-__init__"><strong>__init__</strong></a>(self, text<font color="#909090">=None</font>)</dt></dl> <hr> Static methods defined here:<br> <dl><dt><a name="Hashtag-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data)</dt><dd><tt>Create&nbsp;a&nbsp;new&nbsp;instance&nbsp;based&nbsp;on&nbsp;a&nbsp;JSON&nbsp;dict.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;data:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;JSON&nbsp;dict,&nbsp;as&nbsp;converted&nbsp;from&nbsp;the&nbsp;JSON&nbsp;in&nbsp;the&nbsp;twitter&nbsp;API<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#Hashtag">Hashtag</a>&nbsp;instance</tt></dd></dl> <hr> Data descriptors defined here:<br> <dl><dt><strong>__dict__</strong></dt> <dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>__weakref__</strong></dt> <dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd> </dl> </td></tr></table> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="List">class <strong>List</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr> <tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td> <td colspan=2><tt>A&nbsp;class&nbsp;representing&nbsp;the&nbsp;<a href="#List">List</a>&nbsp;structure&nbsp;used&nbsp;by&nbsp;the&nbsp;twitter&nbsp;API.<br> &nbsp;<br> The&nbsp;<a href="#List">List</a>&nbsp;structure&nbsp;exposes&nbsp;the&nbsp;following&nbsp;properties:<br> &nbsp;<br> &nbsp;&nbsp;list.id<br> &nbsp;&nbsp;list.name<br> &nbsp;&nbsp;list.slug<br> &nbsp;&nbsp;list.description<br> &nbsp;&nbsp;list.full_name<br> &nbsp;&nbsp;list.mode<br> &nbsp;&nbsp;list.uri<br> &nbsp;&nbsp;list.member_count<br> &nbsp;&nbsp;list.subscriber_count<br> &nbsp;&nbsp;list.following<br>&nbsp;</tt></td></tr> <tr><td>&nbsp;</td> <td width="100%">Methods defined here:<br> <dl><dt><a name="List-AsDict"><strong>AsDict</strong></a>(self)</dt><dd><tt>A&nbsp;dict&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#List">List</a>&nbsp;instance.<br> &nbsp;<br> The&nbsp;return&nbsp;value&nbsp;uses&nbsp;the&nbsp;same&nbsp;key&nbsp;names&nbsp;as&nbsp;the&nbsp;JSON&nbsp;representation.<br> &nbsp;<br> Return:<br> &nbsp;&nbsp;A&nbsp;dict&nbsp;representing&nbsp;this&nbsp;twitter.<a href="#List">List</a>&nbsp;instance</tt></dd></dl> <dl><dt><a name="List-AsJsonString"><strong>AsJsonString</strong></a>(self)</dt><dd><tt>A&nbsp;JSON&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#List">List</a>&nbsp;instance.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;JSON&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#List">List</a>&nbsp;instance</tt></dd></dl> <dl><dt><a name="List-GetDescription"><strong>GetDescription</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;description&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;description&nbsp;of&nbsp;this&nbsp;list</tt></dd></dl> <dl><dt><a name="List-GetFollowing"><strong>GetFollowing</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;following&nbsp;status&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;following&nbsp;status&nbsp;of&nbsp;this&nbsp;list</tt></dd></dl> <dl><dt><a name="List-GetFull_name"><strong>GetFull_name</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;full_name&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;full_name&nbsp;of&nbsp;this&nbsp;list</tt></dd></dl> <dl><dt><a name="List-GetId"><strong>GetId</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;list</tt></dd></dl> <dl><dt><a name="List-GetMember_count"><strong>GetMember_count</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;member_count&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;member_count&nbsp;of&nbsp;this&nbsp;list</tt></dd></dl> <dl><dt><a name="List-GetMode"><strong>GetMode</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;mode&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;mode&nbsp;of&nbsp;this&nbsp;list</tt></dd></dl> <dl><dt><a name="List-GetName"><strong>GetName</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;real&nbsp;name&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;real&nbsp;name&nbsp;of&nbsp;this&nbsp;list</tt></dd></dl> <dl><dt><a name="List-GetSlug"><strong>GetSlug</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;slug&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;slug&nbsp;of&nbsp;this&nbsp;list</tt></dd></dl> <dl><dt><a name="List-GetSubscriber_count"><strong>GetSubscriber_count</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;subscriber_count&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;subscriber_count&nbsp;of&nbsp;this&nbsp;list</tt></dd></dl> <dl><dt><a name="List-GetUri"><strong>GetUri</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;uri&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;uri&nbsp;of&nbsp;this&nbsp;list</tt></dd></dl> <dl><dt><a name="List-GetUser"><strong>GetUser</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;user&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;owner&nbsp;of&nbsp;this&nbsp;list</tt></dd></dl> <dl><dt><a name="List-SetDescription"><strong>SetDescription</strong></a>(self, description)</dt><dd><tt>Set&nbsp;the&nbsp;description&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;description:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;description&nbsp;of&nbsp;this&nbsp;list.</tt></dd></dl> <dl><dt><a name="List-SetFollowing"><strong>SetFollowing</strong></a>(self, following)</dt><dd><tt>Set&nbsp;the&nbsp;following&nbsp;status&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;following:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;following&nbsp;of&nbsp;this&nbsp;list.</tt></dd></dl> <dl><dt><a name="List-SetFull_name"><strong>SetFull_name</strong></a>(self, full_name)</dt><dd><tt>Set&nbsp;the&nbsp;full_name&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;full_name:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;full_name&nbsp;of&nbsp;this&nbsp;list.</tt></dd></dl> <dl><dt><a name="List-SetId"><strong>SetId</strong></a>(self, id)</dt><dd><tt>Set&nbsp;the&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;id:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;list.</tt></dd></dl> <dl><dt><a name="List-SetMember_count"><strong>SetMember_count</strong></a>(self, member_count)</dt><dd><tt>Set&nbsp;the&nbsp;member_count&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;member_count:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;member_count&nbsp;of&nbsp;this&nbsp;list.</tt></dd></dl> <dl><dt><a name="List-SetMode"><strong>SetMode</strong></a>(self, mode)</dt><dd><tt>Set&nbsp;the&nbsp;mode&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;mode:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;mode&nbsp;of&nbsp;this&nbsp;list.</tt></dd></dl> <dl><dt><a name="List-SetName"><strong>SetName</strong></a>(self, name)</dt><dd><tt>Set&nbsp;the&nbsp;real&nbsp;name&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;name:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;real&nbsp;name&nbsp;of&nbsp;this&nbsp;list</tt></dd></dl> <dl><dt><a name="List-SetSlug"><strong>SetSlug</strong></a>(self, slug)</dt><dd><tt>Set&nbsp;the&nbsp;slug&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;slug:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;slug&nbsp;of&nbsp;this&nbsp;list.</tt></dd></dl> <dl><dt><a name="List-SetSubscriber_count"><strong>SetSubscriber_count</strong></a>(self, subscriber_count)</dt><dd><tt>Set&nbsp;the&nbsp;subscriber_count&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;subscriber_count:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;subscriber_count&nbsp;of&nbsp;this&nbsp;list.</tt></dd></dl> <dl><dt><a name="List-SetUri"><strong>SetUri</strong></a>(self, uri)</dt><dd><tt>Set&nbsp;the&nbsp;uri&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;uri:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;uri&nbsp;of&nbsp;this&nbsp;list.</tt></dd></dl> <dl><dt><a name="List-SetUser"><strong>SetUser</strong></a>(self, user)</dt><dd><tt>Set&nbsp;the&nbsp;user&nbsp;of&nbsp;this&nbsp;list.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;owner&nbsp;of&nbsp;this&nbsp;list.</tt></dd></dl> <dl><dt><a name="List-__eq__"><strong>__eq__</strong></a>(self, other)</dt></dl> <dl><dt><a name="List-__init__"><strong>__init__</strong></a>(self, id<font color="#909090">=None</font>, name<font color="#909090">=None</font>, slug<font color="#909090">=None</font>, description<font color="#909090">=None</font>, full_name<font color="#909090">=None</font>, mode<font color="#909090">=None</font>, uri<font color="#909090">=None</font>, member_count<font color="#909090">=None</font>, subscriber_count<font color="#909090">=None</font>, following<font color="#909090">=None</font>, user<font color="#909090">=None</font>)</dt></dl> <dl><dt><a name="List-__ne__"><strong>__ne__</strong></a>(self, other)</dt></dl> <dl><dt><a name="List-__str__"><strong>__str__</strong></a>(self)</dt><dd><tt>A&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#List">List</a>&nbsp;instance.<br> &nbsp;<br> The&nbsp;return&nbsp;value&nbsp;is&nbsp;the&nbsp;same&nbsp;as&nbsp;the&nbsp;JSON&nbsp;string&nbsp;representation.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#List">List</a>&nbsp;instance.</tt></dd></dl> <hr> Static methods defined here:<br> <dl><dt><a name="List-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data)</dt><dd><tt>Create&nbsp;a&nbsp;new&nbsp;instance&nbsp;based&nbsp;on&nbsp;a&nbsp;JSON&nbsp;dict.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;data:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;JSON&nbsp;dict,&nbsp;as&nbsp;converted&nbsp;from&nbsp;the&nbsp;JSON&nbsp;in&nbsp;the&nbsp;twitter&nbsp;API<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#List">List</a>&nbsp;instance</tt></dd></dl> <hr> Data descriptors defined here:<br> <dl><dt><strong>__dict__</strong></dt> <dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>__weakref__</strong></dt> <dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>description</strong></dt> <dd><tt>The&nbsp;description&nbsp;of&nbsp;this&nbsp;list.</tt></dd> </dl> <dl><dt><strong>following</strong></dt> <dd><tt>The&nbsp;following&nbsp;status&nbsp;of&nbsp;this&nbsp;list.</tt></dd> </dl> <dl><dt><strong>full_name</strong></dt> <dd><tt>The&nbsp;full_name&nbsp;of&nbsp;this&nbsp;list.</tt></dd> </dl> <dl><dt><strong>id</strong></dt> <dd><tt>The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;list.</tt></dd> </dl> <dl><dt><strong>member_count</strong></dt> <dd><tt>The&nbsp;member_count&nbsp;of&nbsp;this&nbsp;list.</tt></dd> </dl> <dl><dt><strong>mode</strong></dt> <dd><tt>The&nbsp;mode&nbsp;of&nbsp;this&nbsp;list.</tt></dd> </dl> <dl><dt><strong>name</strong></dt> <dd><tt>The&nbsp;real&nbsp;name&nbsp;of&nbsp;this&nbsp;list.</tt></dd> </dl> <dl><dt><strong>slug</strong></dt> <dd><tt>The&nbsp;slug&nbsp;of&nbsp;this&nbsp;list.</tt></dd> </dl> <dl><dt><strong>subscriber_count</strong></dt> <dd><tt>The&nbsp;subscriber_count&nbsp;of&nbsp;this&nbsp;list.</tt></dd> </dl> <dl><dt><strong>uri</strong></dt> <dd><tt>The&nbsp;uri&nbsp;of&nbsp;this&nbsp;list.</tt></dd> </dl> <dl><dt><strong>user</strong></dt> <dd><tt>The&nbsp;owner&nbsp;of&nbsp;this&nbsp;list.</tt></dd> </dl> </td></tr></table> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="Status">class <strong>Status</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr> <tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td> <td colspan=2><tt>A&nbsp;class&nbsp;representing&nbsp;the&nbsp;<a href="#Status">Status</a>&nbsp;structure&nbsp;used&nbsp;by&nbsp;the&nbsp;twitter&nbsp;API.<br> &nbsp;<br> The&nbsp;<a href="#Status">Status</a>&nbsp;structure&nbsp;exposes&nbsp;the&nbsp;following&nbsp;properties:<br> &nbsp;<br> &nbsp;&nbsp;status.created_at<br> &nbsp;&nbsp;status.created_at_in_seconds&nbsp;#&nbsp;read&nbsp;only<br> &nbsp;&nbsp;status.favorited<br> &nbsp;&nbsp;status.in_reply_to_screen_name<br> &nbsp;&nbsp;status.in_reply_to_user_id<br> &nbsp;&nbsp;status.in_reply_to_status_id<br> &nbsp;&nbsp;status.truncated<br> &nbsp;&nbsp;status.source<br> &nbsp;&nbsp;status.id<br> &nbsp;&nbsp;status.text<br> &nbsp;&nbsp;status.location<br> &nbsp;&nbsp;status.relative_created_at&nbsp;#&nbsp;read&nbsp;only<br> &nbsp;&nbsp;status.user<br> &nbsp;&nbsp;status.urls<br> &nbsp;&nbsp;status.user_mentions<br> &nbsp;&nbsp;status.hashtags<br>&nbsp;</tt></td></tr> <tr><td>&nbsp;</td> <td width="100%">Methods defined here:<br> <dl><dt><a name="Status-AsDict"><strong>AsDict</strong></a>(self)</dt><dd><tt>A&nbsp;dict&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance.<br> &nbsp;<br> The&nbsp;return&nbsp;value&nbsp;uses&nbsp;the&nbsp;same&nbsp;key&nbsp;names&nbsp;as&nbsp;the&nbsp;JSON&nbsp;representation.<br> &nbsp;<br> Return:<br> &nbsp;&nbsp;A&nbsp;dict&nbsp;representing&nbsp;this&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance</tt></dd></dl> <dl><dt><a name="Status-AsJsonString"><strong>AsJsonString</strong></a>(self)</dt><dd><tt>A&nbsp;JSON&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;JSON&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance</tt></dd></dl> <dl><dt><a name="Status-GetCreatedAt"><strong>GetCreatedAt</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;time&nbsp;this&nbsp;status&nbsp;message&nbsp;was&nbsp;posted.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;time&nbsp;this&nbsp;status&nbsp;message&nbsp;was&nbsp;posted</tt></dd></dl> <dl><dt><a name="Status-GetCreatedAtInSeconds"><strong>GetCreatedAtInSeconds</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;time&nbsp;this&nbsp;status&nbsp;message&nbsp;was&nbsp;posted,&nbsp;in&nbsp;seconds&nbsp;since&nbsp;the&nbsp;epoch.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;time&nbsp;this&nbsp;status&nbsp;message&nbsp;was&nbsp;posted,&nbsp;in&nbsp;seconds&nbsp;since&nbsp;the&nbsp;epoch.</tt></dd></dl> <dl><dt><a name="Status-GetFavorited"><strong>GetFavorited</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;favorited&nbsp;setting&nbsp;of&nbsp;this&nbsp;status&nbsp;message.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;True&nbsp;if&nbsp;this&nbsp;status&nbsp;message&nbsp;is&nbsp;favorited;&nbsp;False&nbsp;otherwise</tt></dd></dl> <dl><dt><a name="Status-GetId"><strong>GetId</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;status&nbsp;message.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;status&nbsp;message</tt></dd></dl> <dl><dt><a name="Status-GetInReplyToScreenName"><strong>GetInReplyToScreenName</strong></a>(self)</dt></dl> <dl><dt><a name="Status-GetInReplyToStatusId"><strong>GetInReplyToStatusId</strong></a>(self)</dt></dl> <dl><dt><a name="Status-GetInReplyToUserId"><strong>GetInReplyToUserId</strong></a>(self)</dt></dl> <dl><dt><a name="Status-GetLocation"><strong>GetLocation</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;geolocation&nbsp;associated&nbsp;with&nbsp;this&nbsp;status&nbsp;message<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;geolocation&nbsp;string&nbsp;of&nbsp;this&nbsp;status&nbsp;message.</tt></dd></dl> <dl><dt><a name="Status-GetNow"><strong>GetNow</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;wallclock&nbsp;time&nbsp;for&nbsp;this&nbsp;status&nbsp;message.<br> &nbsp;<br> Used&nbsp;to&nbsp;calculate&nbsp;relative_created_at.&nbsp;&nbsp;Defaults&nbsp;to&nbsp;the&nbsp;time<br> the&nbsp;<a href="__builtin__.html#object">object</a>&nbsp;was&nbsp;instantiated.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;Whatever&nbsp;the&nbsp;status&nbsp;instance&nbsp;believes&nbsp;the&nbsp;current&nbsp;time&nbsp;to&nbsp;be,<br> &nbsp;&nbsp;in&nbsp;seconds&nbsp;since&nbsp;the&nbsp;epoch.</tt></dd></dl> <dl><dt><a name="Status-GetRelativeCreatedAt"><strong>GetRelativeCreatedAt</strong></a>(self)</dt><dd><tt>Get&nbsp;a&nbsp;human&nbsp;redable&nbsp;string&nbsp;representing&nbsp;the&nbsp;posting&nbsp;time<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;human&nbsp;readable&nbsp;string&nbsp;representing&nbsp;the&nbsp;posting&nbsp;time</tt></dd></dl> <dl><dt><a name="Status-GetSource"><strong>GetSource</strong></a>(self)</dt></dl> <dl><dt><a name="Status-GetText"><strong>GetText</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;text&nbsp;of&nbsp;this&nbsp;status&nbsp;message.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;text&nbsp;of&nbsp;this&nbsp;status&nbsp;message.</tt></dd></dl> <dl><dt><a name="Status-GetTruncated"><strong>GetTruncated</strong></a>(self)</dt></dl> <dl><dt><a name="Status-GetUser"><strong>GetUser</strong></a>(self)</dt><dd><tt>Get&nbsp;a&nbsp;twitter.<a href="#User">User</a>&nbsp;reprenting&nbsp;the&nbsp;entity&nbsp;posting&nbsp;this&nbsp;status&nbsp;message.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#User">User</a>&nbsp;reprenting&nbsp;the&nbsp;entity&nbsp;posting&nbsp;this&nbsp;status&nbsp;message</tt></dd></dl> <dl><dt><a name="Status-SetCreatedAt"><strong>SetCreatedAt</strong></a>(self, created_at)</dt><dd><tt>Set&nbsp;the&nbsp;time&nbsp;this&nbsp;status&nbsp;message&nbsp;was&nbsp;posted.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;created_at:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;time&nbsp;this&nbsp;status&nbsp;message&nbsp;was&nbsp;created</tt></dd></dl> <dl><dt><a name="Status-SetFavorited"><strong>SetFavorited</strong></a>(self, favorited)</dt><dd><tt>Set&nbsp;the&nbsp;favorited&nbsp;state&nbsp;of&nbsp;this&nbsp;status&nbsp;message.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;favorited:<br> &nbsp;&nbsp;&nbsp;&nbsp;boolean&nbsp;True/False&nbsp;favorited&nbsp;state&nbsp;of&nbsp;this&nbsp;status&nbsp;message</tt></dd></dl> <dl><dt><a name="Status-SetId"><strong>SetId</strong></a>(self, id)</dt><dd><tt>Set&nbsp;the&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;status&nbsp;message.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;id:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;status&nbsp;message</tt></dd></dl> <dl><dt><a name="Status-SetInReplyToScreenName"><strong>SetInReplyToScreenName</strong></a>(self, in_reply_to_screen_name)</dt></dl> <dl><dt><a name="Status-SetInReplyToStatusId"><strong>SetInReplyToStatusId</strong></a>(self, in_reply_to_status_id)</dt></dl> <dl><dt><a name="Status-SetInReplyToUserId"><strong>SetInReplyToUserId</strong></a>(self, in_reply_to_user_id)</dt></dl> <dl><dt><a name="Status-SetLocation"><strong>SetLocation</strong></a>(self, location)</dt><dd><tt>Set&nbsp;the&nbsp;geolocation&nbsp;associated&nbsp;with&nbsp;this&nbsp;status&nbsp;message<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;location:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;geolocation&nbsp;string&nbsp;of&nbsp;this&nbsp;status&nbsp;message</tt></dd></dl> <dl><dt><a name="Status-SetNow"><strong>SetNow</strong></a>(self, now)</dt><dd><tt>Set&nbsp;the&nbsp;wallclock&nbsp;time&nbsp;for&nbsp;this&nbsp;status&nbsp;message.<br> &nbsp;<br> Used&nbsp;to&nbsp;calculate&nbsp;relative_created_at.&nbsp;&nbsp;Defaults&nbsp;to&nbsp;the&nbsp;time<br> the&nbsp;<a href="__builtin__.html#object">object</a>&nbsp;was&nbsp;instantiated.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;now:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;wallclock&nbsp;time&nbsp;for&nbsp;this&nbsp;instance.</tt></dd></dl> <dl><dt><a name="Status-SetSource"><strong>SetSource</strong></a>(self, source)</dt></dl> <dl><dt><a name="Status-SetText"><strong>SetText</strong></a>(self, text)</dt><dd><tt>Set&nbsp;the&nbsp;text&nbsp;of&nbsp;this&nbsp;status&nbsp;message.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;text:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;text&nbsp;of&nbsp;this&nbsp;status&nbsp;message</tt></dd></dl> <dl><dt><a name="Status-SetTruncated"><strong>SetTruncated</strong></a>(self, truncated)</dt></dl> <dl><dt><a name="Status-SetUser"><strong>SetUser</strong></a>(self, user)</dt><dd><tt>Set&nbsp;a&nbsp;twitter.<a href="#User">User</a>&nbsp;reprenting&nbsp;the&nbsp;entity&nbsp;posting&nbsp;this&nbsp;status&nbsp;message.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;user:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;twitter.<a href="#User">User</a>&nbsp;reprenting&nbsp;the&nbsp;entity&nbsp;posting&nbsp;this&nbsp;status&nbsp;message</tt></dd></dl> <dl><dt><a name="Status-__eq__"><strong>__eq__</strong></a>(self, other)</dt></dl> <dl><dt><a name="Status-__init__"><strong>__init__</strong></a>(self, created_at<font color="#909090">=None</font>, favorited<font color="#909090">=None</font>, id<font color="#909090">=None</font>, text<font color="#909090">=None</font>, location<font color="#909090">=None</font>, user<font color="#909090">=None</font>, in_reply_to_screen_name<font color="#909090">=None</font>, in_reply_to_user_id<font color="#909090">=None</font>, in_reply_to_status_id<font color="#909090">=None</font>, truncated<font color="#909090">=None</font>, source<font color="#909090">=None</font>, now<font color="#909090">=None</font>, urls<font color="#909090">=None</font>, user_mentions<font color="#909090">=None</font>, hashtags<font color="#909090">=None</font>)</dt><dd><tt>An&nbsp;<a href="__builtin__.html#object">object</a>&nbsp;to&nbsp;hold&nbsp;a&nbsp;Twitter&nbsp;status&nbsp;message.<br> &nbsp;<br> This&nbsp;class&nbsp;is&nbsp;normally&nbsp;instantiated&nbsp;by&nbsp;the&nbsp;twitter.<a href="#Api">Api</a>&nbsp;class&nbsp;and<br> returned&nbsp;in&nbsp;a&nbsp;sequence.<br> &nbsp;<br> Note:&nbsp;Dates&nbsp;are&nbsp;posted&nbsp;in&nbsp;the&nbsp;form&nbsp;"Sat&nbsp;Jan&nbsp;27&nbsp;04:17:38&nbsp;+0000&nbsp;2007"<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;created_at:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;time&nbsp;this&nbsp;status&nbsp;message&nbsp;was&nbsp;posted.&nbsp;[Optiona]<br> &nbsp;&nbsp;favorited:<br> &nbsp;&nbsp;&nbsp;&nbsp;Whether&nbsp;this&nbsp;is&nbsp;a&nbsp;favorite&nbsp;of&nbsp;the&nbsp;authenticated&nbsp;user.&nbsp;[Optiona]<br> &nbsp;&nbsp;id:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;status&nbsp;message.&nbsp;[Optiona]<br> &nbsp;&nbsp;text:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;text&nbsp;of&nbsp;this&nbsp;status&nbsp;message.&nbsp;[Optiona]<br> &nbsp;&nbsp;location:<br> &nbsp;&nbsp;&nbsp;&nbsp;the&nbsp;geolocation&nbsp;string&nbsp;associated&nbsp;with&nbsp;this&nbsp;message.&nbsp;[Optiona]<br> &nbsp;&nbsp;relative_created_at:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;human&nbsp;readable&nbsp;string&nbsp;representing&nbsp;the&nbsp;posting&nbsp;time.&nbsp;[Optiona]<br> &nbsp;&nbsp;user:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;twitter.<a href="#User">User</a>&nbsp;instance&nbsp;representing&nbsp;the&nbsp;person&nbsp;posting&nbsp;the<br> &nbsp;&nbsp;&nbsp;&nbsp;message.&nbsp;[Optiona]<br> &nbsp;&nbsp;now:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;current&nbsp;time,&nbsp;if&nbsp;the&nbsp;client&nbsp;choses&nbsp;to&nbsp;set&nbsp;it.<br> &nbsp;&nbsp;&nbsp;&nbsp;Defaults&nbsp;to&nbsp;the&nbsp;wall&nbsp;clock&nbsp;time.&nbsp;[Optiona]</tt></dd></dl> <dl><dt><a name="Status-__ne__"><strong>__ne__</strong></a>(self, other)</dt></dl> <dl><dt><a name="Status-__str__"><strong>__str__</strong></a>(self)</dt><dd><tt>A&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance.<br> &nbsp;<br> The&nbsp;return&nbsp;value&nbsp;is&nbsp;the&nbsp;same&nbsp;as&nbsp;the&nbsp;JSON&nbsp;string&nbsp;representation.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance.</tt></dd></dl> <hr> Static methods defined here:<br> <dl><dt><a name="Status-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data)</dt><dd><tt>Create&nbsp;a&nbsp;new&nbsp;instance&nbsp;based&nbsp;on&nbsp;a&nbsp;JSON&nbsp;dict.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;data:&nbsp;A&nbsp;JSON&nbsp;dict,&nbsp;as&nbsp;converted&nbsp;from&nbsp;the&nbsp;JSON&nbsp;in&nbsp;the&nbsp;twitter&nbsp;API<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#Status">Status</a>&nbsp;instance</tt></dd></dl> <hr> Data descriptors defined here:<br> <dl><dt><strong>__dict__</strong></dt> <dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>__weakref__</strong></dt> <dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>created_at</strong></dt> <dd><tt>The&nbsp;time&nbsp;this&nbsp;status&nbsp;message&nbsp;was&nbsp;posted.</tt></dd> </dl> <dl><dt><strong>created_at_in_seconds</strong></dt> <dd><tt>The&nbsp;time&nbsp;this&nbsp;status&nbsp;message&nbsp;was&nbsp;posted,&nbsp;in&nbsp;seconds&nbsp;since&nbsp;the&nbsp;epoch</tt></dd> </dl> <dl><dt><strong>favorited</strong></dt> <dd><tt>The&nbsp;favorited&nbsp;state&nbsp;of&nbsp;this&nbsp;status&nbsp;message.</tt></dd> </dl> <dl><dt><strong>id</strong></dt> <dd><tt>The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;status&nbsp;message.</tt></dd> </dl> <dl><dt><strong>in_reply_to_screen_name</strong></dt> <dd><tt></tt></dd> </dl> <dl><dt><strong>in_reply_to_status_id</strong></dt> <dd><tt></tt></dd> </dl> <dl><dt><strong>in_reply_to_user_id</strong></dt> <dd><tt></tt></dd> </dl> <dl><dt><strong>location</strong></dt> <dd><tt>The&nbsp;geolocation&nbsp;string&nbsp;of&nbsp;this&nbsp;status&nbsp;message</tt></dd> </dl> <dl><dt><strong>now</strong></dt> <dd><tt>The&nbsp;wallclock&nbsp;time&nbsp;for&nbsp;this&nbsp;status&nbsp;instance.</tt></dd> </dl> <dl><dt><strong>relative_created_at</strong></dt> <dd><tt>Get&nbsp;a&nbsp;human&nbsp;readable&nbsp;string&nbsp;representing&nbsp;the&nbsp;posting&nbsp;time</tt></dd> </dl> <dl><dt><strong>source</strong></dt> <dd><tt></tt></dd> </dl> <dl><dt><strong>text</strong></dt> <dd><tt>The&nbsp;text&nbsp;of&nbsp;this&nbsp;status&nbsp;message</tt></dd> </dl> <dl><dt><strong>truncated</strong></dt> <dd><tt></tt></dd> </dl> <dl><dt><strong>user</strong></dt> <dd><tt>A&nbsp;twitter.User&nbsp;reprenting&nbsp;the&nbsp;entity&nbsp;posting&nbsp;this&nbsp;status&nbsp;message</tt></dd> </dl> </td></tr></table> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="Trend">class <strong>Trend</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr> <tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td> <td colspan=2><tt>A&nbsp;class&nbsp;representing&nbsp;a&nbsp;trending&nbsp;topic<br>&nbsp;</tt></td></tr> <tr><td>&nbsp;</td> <td width="100%">Methods defined here:<br> <dl><dt><a name="Trend-__init__"><strong>__init__</strong></a>(self, name<font color="#909090">=None</font>, query<font color="#909090">=None</font>, timestamp<font color="#909090">=None</font>)</dt></dl> <dl><dt><a name="Trend-__str__"><strong>__str__</strong></a>(self)</dt></dl> <hr> Static methods defined here:<br> <dl><dt><a name="Trend-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data, timestamp<font color="#909090">=None</font>)</dt><dd><tt>Create&nbsp;a&nbsp;new&nbsp;instance&nbsp;based&nbsp;on&nbsp;a&nbsp;JSON&nbsp;dict<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;data:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;JSON&nbsp;dict<br> &nbsp;&nbsp;timestamp:<br> &nbsp;&nbsp;&nbsp;&nbsp;Gets&nbsp;set&nbsp;as&nbsp;the&nbsp;timestamp&nbsp;property&nbsp;of&nbsp;the&nbsp;new&nbsp;<a href="__builtin__.html#object">object</a><br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#Trend">Trend</a>&nbsp;<a href="__builtin__.html#object">object</a></tt></dd></dl> <hr> Data descriptors defined here:<br> <dl><dt><strong>__dict__</strong></dt> <dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>__weakref__</strong></dt> <dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd> </dl> </td></tr></table> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="TwitterError">class <strong>TwitterError</strong></a>(<a href="exceptions.html#Exception">exceptions.Exception</a>)</font></td></tr> <tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td> <td colspan=2><tt>Base&nbsp;class&nbsp;for&nbsp;Twitter&nbsp;errors<br>&nbsp;</tt></td></tr> <tr><td>&nbsp;</td> <td width="100%"><dl><dt>Method resolution order:</dt> <dd><a href="twitter.html#TwitterError">TwitterError</a></dd> <dd><a href="exceptions.html#Exception">exceptions.Exception</a></dd> <dd><a href="exceptions.html#BaseException">exceptions.BaseException</a></dd> <dd><a href="__builtin__.html#object">__builtin__.object</a></dd> </dl> <hr> Data descriptors defined here:<br> <dl><dt><strong>__weakref__</strong></dt> <dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>message</strong></dt> <dd><tt>Returns&nbsp;the&nbsp;first&nbsp;argument&nbsp;used&nbsp;to&nbsp;construct&nbsp;this&nbsp;error.</tt></dd> </dl> <hr> Methods inherited from <a href="exceptions.html#Exception">exceptions.Exception</a>:<br> <dl><dt><a name="TwitterError-__init__"><strong>__init__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__init__">__init__</a>(...)&nbsp;initializes&nbsp;x;&nbsp;see&nbsp;x.__class__.__doc__&nbsp;for&nbsp;signature</tt></dd></dl> <hr> Data and other attributes inherited from <a href="exceptions.html#Exception">exceptions.Exception</a>:<br> <dl><dt><strong>__new__</strong> = &lt;built-in method __new__ of type object at 0x100119f80&gt;<dd><tt>T.<a href="#TwitterError-__new__">__new__</a>(S,&nbsp;...)&nbsp;-&gt;&nbsp;a&nbsp;new&nbsp;<a href="__builtin__.html#object">object</a>&nbsp;with&nbsp;type&nbsp;S,&nbsp;a&nbsp;subtype&nbsp;of&nbsp;T</tt></dl> <hr> Methods inherited from <a href="exceptions.html#BaseException">exceptions.BaseException</a>:<br> <dl><dt><a name="TwitterError-__delattr__"><strong>__delattr__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__delattr__">__delattr__</a>('name')&nbsp;&lt;==&gt;&nbsp;del&nbsp;x.name</tt></dd></dl> <dl><dt><a name="TwitterError-__getattribute__"><strong>__getattribute__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__getattribute__">__getattribute__</a>('name')&nbsp;&lt;==&gt;&nbsp;x.name</tt></dd></dl> <dl><dt><a name="TwitterError-__getitem__"><strong>__getitem__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__getitem__">__getitem__</a>(y)&nbsp;&lt;==&gt;&nbsp;x[y]</tt></dd></dl> <dl><dt><a name="TwitterError-__getslice__"><strong>__getslice__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__getslice__">__getslice__</a>(i,&nbsp;j)&nbsp;&lt;==&gt;&nbsp;x[i:j]<br> &nbsp;<br> Use&nbsp;of&nbsp;negative&nbsp;indices&nbsp;is&nbsp;not&nbsp;supported.</tt></dd></dl> <dl><dt><a name="TwitterError-__reduce__"><strong>__reduce__</strong></a>(...)</dt></dl> <dl><dt><a name="TwitterError-__repr__"><strong>__repr__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__repr__">__repr__</a>()&nbsp;&lt;==&gt;&nbsp;repr(x)</tt></dd></dl> <dl><dt><a name="TwitterError-__setattr__"><strong>__setattr__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__setattr__">__setattr__</a>('name',&nbsp;value)&nbsp;&lt;==&gt;&nbsp;x.name&nbsp;=&nbsp;value</tt></dd></dl> <dl><dt><a name="TwitterError-__setstate__"><strong>__setstate__</strong></a>(...)</dt></dl> <dl><dt><a name="TwitterError-__str__"><strong>__str__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__str__">__str__</a>()&nbsp;&lt;==&gt;&nbsp;str(x)</tt></dd></dl> <dl><dt><a name="TwitterError-__unicode__"><strong>__unicode__</strong></a>(...)</dt></dl> <hr> Data descriptors inherited from <a href="exceptions.html#BaseException">exceptions.BaseException</a>:<br> <dl><dt><strong>__dict__</strong></dt> </dl> <dl><dt><strong>args</strong></dt> </dl> </td></tr></table> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="Url">class <strong>Url</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr> <tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td> <td colspan=2><tt>A&nbsp;class&nbsp;representing&nbsp;an&nbsp;URL&nbsp;contained&nbsp;in&nbsp;a&nbsp;tweet<br>&nbsp;</tt></td></tr> <tr><td>&nbsp;</td> <td width="100%">Methods defined here:<br> <dl><dt><a name="Url-__init__"><strong>__init__</strong></a>(self, url<font color="#909090">=None</font>, expanded_url<font color="#909090">=None</font>)</dt></dl> <hr> Static methods defined here:<br> <dl><dt><a name="Url-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data)</dt><dd><tt>Create&nbsp;a&nbsp;new&nbsp;instance&nbsp;based&nbsp;on&nbsp;a&nbsp;JSON&nbsp;dict.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;data:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;JSON&nbsp;dict,&nbsp;as&nbsp;converted&nbsp;from&nbsp;the&nbsp;JSON&nbsp;in&nbsp;the&nbsp;twitter&nbsp;API<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#Url">Url</a>&nbsp;instance</tt></dd></dl> <hr> Data descriptors defined here:<br> <dl><dt><strong>__dict__</strong></dt> <dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>__weakref__</strong></dt> <dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd> </dl> </td></tr></table> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="User">class <strong>User</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr> <tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td> <td colspan=2><tt>A&nbsp;class&nbsp;representing&nbsp;the&nbsp;<a href="#User">User</a>&nbsp;structure&nbsp;used&nbsp;by&nbsp;the&nbsp;twitter&nbsp;API.<br> &nbsp;<br> The&nbsp;<a href="#User">User</a>&nbsp;structure&nbsp;exposes&nbsp;the&nbsp;following&nbsp;properties:<br> &nbsp;<br> &nbsp;&nbsp;user.id<br> &nbsp;&nbsp;user.name<br> &nbsp;&nbsp;user.screen_name<br> &nbsp;&nbsp;user.location<br> &nbsp;&nbsp;user.description<br> &nbsp;&nbsp;user.profile_image_url<br> &nbsp;&nbsp;user.profile_background_tile<br> &nbsp;&nbsp;user.profile_background_image_url<br> &nbsp;&nbsp;user.profile_sidebar_fill_color<br> &nbsp;&nbsp;user.profile_background_color<br> &nbsp;&nbsp;user.profile_link_color<br> &nbsp;&nbsp;user.profile_text_color<br> &nbsp;&nbsp;user.protected<br> &nbsp;&nbsp;user.utc_offset<br> &nbsp;&nbsp;user.time_zone<br> &nbsp;&nbsp;user.url<br> &nbsp;&nbsp;user.status<br> &nbsp;&nbsp;user.statuses_count<br> &nbsp;&nbsp;user.followers_count<br> &nbsp;&nbsp;user.friends_count<br> &nbsp;&nbsp;user.favourites_count<br>&nbsp;</tt></td></tr> <tr><td>&nbsp;</td> <td width="100%">Methods defined here:<br> <dl><dt><a name="User-AsDict"><strong>AsDict</strong></a>(self)</dt><dd><tt>A&nbsp;dict&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#User">User</a>&nbsp;instance.<br> &nbsp;<br> The&nbsp;return&nbsp;value&nbsp;uses&nbsp;the&nbsp;same&nbsp;key&nbsp;names&nbsp;as&nbsp;the&nbsp;JSON&nbsp;representation.<br> &nbsp;<br> Return:<br> &nbsp;&nbsp;A&nbsp;dict&nbsp;representing&nbsp;this&nbsp;twitter.<a href="#User">User</a>&nbsp;instance</tt></dd></dl> <dl><dt><a name="User-AsJsonString"><strong>AsJsonString</strong></a>(self)</dt><dd><tt>A&nbsp;JSON&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#User">User</a>&nbsp;instance.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;JSON&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#User">User</a>&nbsp;instance</tt></dd></dl> <dl><dt><a name="User-GetDescription"><strong>GetDescription</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;short&nbsp;text&nbsp;description&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;short&nbsp;text&nbsp;description&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-GetFavouritesCount"><strong>GetFavouritesCount</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;number&nbsp;of&nbsp;favourites&nbsp;for&nbsp;this&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;number&nbsp;of&nbsp;favourites&nbsp;for&nbsp;this&nbsp;user.</tt></dd></dl> <dl><dt><a name="User-GetFollowersCount"><strong>GetFollowersCount</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;follower&nbsp;count&nbsp;for&nbsp;this&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;number&nbsp;of&nbsp;users&nbsp;following&nbsp;this&nbsp;user.</tt></dd></dl> <dl><dt><a name="User-GetFriendsCount"><strong>GetFriendsCount</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;friend&nbsp;count&nbsp;for&nbsp;this&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;number&nbsp;of&nbsp;users&nbsp;this&nbsp;user&nbsp;has&nbsp;befriended.</tt></dd></dl> <dl><dt><a name="User-GetId"><strong>GetId</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-GetLocation"><strong>GetLocation</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;geographic&nbsp;location&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;geographic&nbsp;location&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-GetName"><strong>GetName</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;real&nbsp;name&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;real&nbsp;name&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-GetProfileBackgroundColor"><strong>GetProfileBackgroundColor</strong></a>(self)</dt></dl> <dl><dt><a name="User-GetProfileBackgroundImageUrl"><strong>GetProfileBackgroundImageUrl</strong></a>(self)</dt></dl> <dl><dt><a name="User-GetProfileBackgroundTile"><strong>GetProfileBackgroundTile</strong></a>(self)</dt><dd><tt>Boolean&nbsp;for&nbsp;whether&nbsp;to&nbsp;tile&nbsp;the&nbsp;profile&nbsp;background&nbsp;image.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;True&nbsp;if&nbsp;the&nbsp;background&nbsp;is&nbsp;to&nbsp;be&nbsp;tiled,&nbsp;False&nbsp;if&nbsp;not,&nbsp;None&nbsp;if&nbsp;unset.</tt></dd></dl> <dl><dt><a name="User-GetProfileImageUrl"><strong>GetProfileImageUrl</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;url&nbsp;of&nbsp;the&nbsp;thumbnail&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;url&nbsp;of&nbsp;the&nbsp;thumbnail&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-GetProfileLinkColor"><strong>GetProfileLinkColor</strong></a>(self)</dt></dl> <dl><dt><a name="User-GetProfileSidebarFillColor"><strong>GetProfileSidebarFillColor</strong></a>(self)</dt></dl> <dl><dt><a name="User-GetProfileTextColor"><strong>GetProfileTextColor</strong></a>(self)</dt></dl> <dl><dt><a name="User-GetProtected"><strong>GetProtected</strong></a>(self)</dt></dl> <dl><dt><a name="User-GetScreenName"><strong>GetScreenName</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;short&nbsp;twitter&nbsp;name&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;short&nbsp;twitter&nbsp;name&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-GetStatus"><strong>GetStatus</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;latest&nbsp;twitter.<a href="#Status">Status</a>&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;latest&nbsp;twitter.<a href="#Status">Status</a>&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-GetStatusesCount"><strong>GetStatusesCount</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;number&nbsp;of&nbsp;status&nbsp;updates&nbsp;for&nbsp;this&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;number&nbsp;of&nbsp;status&nbsp;updates&nbsp;for&nbsp;this&nbsp;user.</tt></dd></dl> <dl><dt><a name="User-GetTimeZone"><strong>GetTimeZone</strong></a>(self)</dt><dd><tt>Returns&nbsp;the&nbsp;current&nbsp;time&nbsp;zone&nbsp;string&nbsp;for&nbsp;the&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;descriptive&nbsp;time&nbsp;zone&nbsp;string&nbsp;for&nbsp;the&nbsp;user.</tt></dd></dl> <dl><dt><a name="User-GetUrl"><strong>GetUrl</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;homepage&nbsp;url&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;homepage&nbsp;url&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-GetUtcOffset"><strong>GetUtcOffset</strong></a>(self)</dt></dl> <dl><dt><a name="User-SetDescription"><strong>SetDescription</strong></a>(self, description)</dt><dd><tt>Set&nbsp;the&nbsp;short&nbsp;text&nbsp;description&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;description:&nbsp;The&nbsp;short&nbsp;text&nbsp;description&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-SetFavouritesCount"><strong>SetFavouritesCount</strong></a>(self, count)</dt><dd><tt>Set&nbsp;the&nbsp;favourite&nbsp;count&nbsp;for&nbsp;this&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;count:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;number&nbsp;of&nbsp;favourites&nbsp;for&nbsp;this&nbsp;user.</tt></dd></dl> <dl><dt><a name="User-SetFollowersCount"><strong>SetFollowersCount</strong></a>(self, count)</dt><dd><tt>Set&nbsp;the&nbsp;follower&nbsp;count&nbsp;for&nbsp;this&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;count:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;number&nbsp;of&nbsp;users&nbsp;following&nbsp;this&nbsp;user.</tt></dd></dl> <dl><dt><a name="User-SetFriendsCount"><strong>SetFriendsCount</strong></a>(self, count)</dt><dd><tt>Set&nbsp;the&nbsp;friend&nbsp;count&nbsp;for&nbsp;this&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;count:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;number&nbsp;of&nbsp;users&nbsp;this&nbsp;user&nbsp;has&nbsp;befriended.</tt></dd></dl> <dl><dt><a name="User-SetId"><strong>SetId</strong></a>(self, id)</dt><dd><tt>Set&nbsp;the&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;id:&nbsp;The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;user.</tt></dd></dl> <dl><dt><a name="User-SetLocation"><strong>SetLocation</strong></a>(self, location)</dt><dd><tt>Set&nbsp;the&nbsp;geographic&nbsp;location&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;location:&nbsp;The&nbsp;geographic&nbsp;location&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-SetName"><strong>SetName</strong></a>(self, name)</dt><dd><tt>Set&nbsp;the&nbsp;real&nbsp;name&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;name:&nbsp;The&nbsp;real&nbsp;name&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-SetProfileBackgroundColor"><strong>SetProfileBackgroundColor</strong></a>(self, profile_background_color)</dt></dl> <dl><dt><a name="User-SetProfileBackgroundImageUrl"><strong>SetProfileBackgroundImageUrl</strong></a>(self, profile_background_image_url)</dt></dl> <dl><dt><a name="User-SetProfileBackgroundTile"><strong>SetProfileBackgroundTile</strong></a>(self, profile_background_tile)</dt><dd><tt>Set&nbsp;the&nbsp;boolean&nbsp;flag&nbsp;for&nbsp;whether&nbsp;to&nbsp;tile&nbsp;the&nbsp;profile&nbsp;background&nbsp;image.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;profile_background_tile:&nbsp;Boolean&nbsp;flag&nbsp;for&nbsp;whether&nbsp;to&nbsp;tile&nbsp;or&nbsp;not.</tt></dd></dl> <dl><dt><a name="User-SetProfileImageUrl"><strong>SetProfileImageUrl</strong></a>(self, profile_image_url)</dt><dd><tt>Set&nbsp;the&nbsp;url&nbsp;of&nbsp;the&nbsp;thumbnail&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;profile_image_url:&nbsp;The&nbsp;url&nbsp;of&nbsp;the&nbsp;thumbnail&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-SetProfileLinkColor"><strong>SetProfileLinkColor</strong></a>(self, profile_link_color)</dt></dl> <dl><dt><a name="User-SetProfileSidebarFillColor"><strong>SetProfileSidebarFillColor</strong></a>(self, profile_sidebar_fill_color)</dt></dl> <dl><dt><a name="User-SetProfileTextColor"><strong>SetProfileTextColor</strong></a>(self, profile_text_color)</dt></dl> <dl><dt><a name="User-SetProtected"><strong>SetProtected</strong></a>(self, protected)</dt></dl> <dl><dt><a name="User-SetScreenName"><strong>SetScreenName</strong></a>(self, screen_name)</dt><dd><tt>Set&nbsp;the&nbsp;short&nbsp;twitter&nbsp;name&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;screen_name:&nbsp;the&nbsp;short&nbsp;twitter&nbsp;name&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-SetStatus"><strong>SetStatus</strong></a>(self, status)</dt><dd><tt>Set&nbsp;the&nbsp;latest&nbsp;twitter.<a href="#Status">Status</a>&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;status:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;latest&nbsp;twitter.<a href="#Status">Status</a>&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-SetStatusesCount"><strong>SetStatusesCount</strong></a>(self, count)</dt><dd><tt>Set&nbsp;the&nbsp;status&nbsp;update&nbsp;count&nbsp;for&nbsp;this&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;count:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;number&nbsp;of&nbsp;updates&nbsp;for&nbsp;this&nbsp;user.</tt></dd></dl> <dl><dt><a name="User-SetTimeZone"><strong>SetTimeZone</strong></a>(self, time_zone)</dt><dd><tt>Sets&nbsp;the&nbsp;user's&nbsp;time&nbsp;zone&nbsp;string.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;time_zone:<br> &nbsp;&nbsp;&nbsp;&nbsp;The&nbsp;descriptive&nbsp;time&nbsp;zone&nbsp;to&nbsp;assign&nbsp;for&nbsp;the&nbsp;user.</tt></dd></dl> <dl><dt><a name="User-SetUrl"><strong>SetUrl</strong></a>(self, url)</dt><dd><tt>Set&nbsp;the&nbsp;homepage&nbsp;url&nbsp;of&nbsp;this&nbsp;user.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;url:&nbsp;The&nbsp;homepage&nbsp;url&nbsp;of&nbsp;this&nbsp;user</tt></dd></dl> <dl><dt><a name="User-SetUtcOffset"><strong>SetUtcOffset</strong></a>(self, utc_offset)</dt></dl> <dl><dt><a name="User-__eq__"><strong>__eq__</strong></a>(self, other)</dt></dl> <dl><dt><a name="User-__init__"><strong>__init__</strong></a>(self, id<font color="#909090">=None</font>, name<font color="#909090">=None</font>, screen_name<font color="#909090">=None</font>, location<font color="#909090">=None</font>, description<font color="#909090">=None</font>, profile_image_url<font color="#909090">=None</font>, profile_background_tile<font color="#909090">=None</font>, profile_background_image_url<font color="#909090">=None</font>, profile_sidebar_fill_color<font color="#909090">=None</font>, profile_background_color<font color="#909090">=None</font>, profile_link_color<font color="#909090">=None</font>, profile_text_color<font color="#909090">=None</font>, protected<font color="#909090">=None</font>, utc_offset<font color="#909090">=None</font>, time_zone<font color="#909090">=None</font>, followers_count<font color="#909090">=None</font>, friends_count<font color="#909090">=None</font>, statuses_count<font color="#909090">=None</font>, favourites_count<font color="#909090">=None</font>, url<font color="#909090">=None</font>, status<font color="#909090">=None</font>)</dt></dl> <dl><dt><a name="User-__ne__"><strong>__ne__</strong></a>(self, other)</dt></dl> <dl><dt><a name="User-__str__"><strong>__str__</strong></a>(self)</dt><dd><tt>A&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#User">User</a>&nbsp;instance.<br> &nbsp;<br> The&nbsp;return&nbsp;value&nbsp;is&nbsp;the&nbsp;same&nbsp;as&nbsp;the&nbsp;JSON&nbsp;string&nbsp;representation.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;string&nbsp;representation&nbsp;of&nbsp;this&nbsp;twitter.<a href="#User">User</a>&nbsp;instance.</tt></dd></dl> <hr> Static methods defined here:<br> <dl><dt><a name="User-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data)</dt><dd><tt>Create&nbsp;a&nbsp;new&nbsp;instance&nbsp;based&nbsp;on&nbsp;a&nbsp;JSON&nbsp;dict.<br> &nbsp;<br> Args:<br> &nbsp;&nbsp;data:<br> &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;JSON&nbsp;dict,&nbsp;as&nbsp;converted&nbsp;from&nbsp;the&nbsp;JSON&nbsp;in&nbsp;the&nbsp;twitter&nbsp;API<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;A&nbsp;twitter.<a href="#User">User</a>&nbsp;instance</tt></dd></dl> <hr> Data descriptors defined here:<br> <dl><dt><strong>__dict__</strong></dt> <dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>__weakref__</strong></dt> <dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>description</strong></dt> <dd><tt>The&nbsp;short&nbsp;text&nbsp;description&nbsp;of&nbsp;this&nbsp;user.</tt></dd> </dl> <dl><dt><strong>favourites_count</strong></dt> <dd><tt>The&nbsp;number&nbsp;of&nbsp;favourites&nbsp;for&nbsp;this&nbsp;user.</tt></dd> </dl> <dl><dt><strong>followers_count</strong></dt> <dd><tt>The&nbsp;number&nbsp;of&nbsp;users&nbsp;following&nbsp;this&nbsp;user.</tt></dd> </dl> <dl><dt><strong>friends_count</strong></dt> <dd><tt>The&nbsp;number&nbsp;of&nbsp;friends&nbsp;for&nbsp;this&nbsp;user.</tt></dd> </dl> <dl><dt><strong>id</strong></dt> <dd><tt>The&nbsp;unique&nbsp;id&nbsp;of&nbsp;this&nbsp;user.</tt></dd> </dl> <dl><dt><strong>location</strong></dt> <dd><tt>The&nbsp;geographic&nbsp;location&nbsp;of&nbsp;this&nbsp;user.</tt></dd> </dl> <dl><dt><strong>name</strong></dt> <dd><tt>The&nbsp;real&nbsp;name&nbsp;of&nbsp;this&nbsp;user.</tt></dd> </dl> <dl><dt><strong>profile_background_color</strong></dt> </dl> <dl><dt><strong>profile_background_image_url</strong></dt> <dd><tt>The&nbsp;url&nbsp;of&nbsp;the&nbsp;profile&nbsp;background&nbsp;of&nbsp;this&nbsp;user.</tt></dd> </dl> <dl><dt><strong>profile_background_tile</strong></dt> <dd><tt>Boolean&nbsp;for&nbsp;whether&nbsp;to&nbsp;tile&nbsp;the&nbsp;background&nbsp;image.</tt></dd> </dl> <dl><dt><strong>profile_image_url</strong></dt> <dd><tt>The&nbsp;url&nbsp;of&nbsp;the&nbsp;thumbnail&nbsp;of&nbsp;this&nbsp;user.</tt></dd> </dl> <dl><dt><strong>profile_link_color</strong></dt> </dl> <dl><dt><strong>profile_sidebar_fill_color</strong></dt> </dl> <dl><dt><strong>profile_text_color</strong></dt> </dl> <dl><dt><strong>protected</strong></dt> </dl> <dl><dt><strong>screen_name</strong></dt> <dd><tt>The&nbsp;short&nbsp;twitter&nbsp;name&nbsp;of&nbsp;this&nbsp;user.</tt></dd> </dl> <dl><dt><strong>status</strong></dt> <dd><tt>The&nbsp;latest&nbsp;twitter.Status&nbsp;of&nbsp;this&nbsp;user.</tt></dd> </dl> <dl><dt><strong>statuses_count</strong></dt> <dd><tt>The&nbsp;number&nbsp;of&nbsp;updates&nbsp;for&nbsp;this&nbsp;user.</tt></dd> </dl> <dl><dt><strong>time_zone</strong></dt> <dd><tt>Returns&nbsp;the&nbsp;current&nbsp;time&nbsp;zone&nbsp;string&nbsp;for&nbsp;the&nbsp;user.<br> &nbsp;<br> Returns:<br> &nbsp;&nbsp;The&nbsp;descriptive&nbsp;time&nbsp;zone&nbsp;string&nbsp;for&nbsp;the&nbsp;user.</tt></dd> </dl> <dl><dt><strong>url</strong></dt> <dd><tt>The&nbsp;homepage&nbsp;url&nbsp;of&nbsp;this&nbsp;user.</tt></dd> </dl> <dl><dt><strong>utc_offset</strong></dt> </dl> </td></tr></table></td></tr></table><p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#eeaa77"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr> <tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%"><dl><dt><a name="-md5"><strong>md5</strong></a> = openssl_md5(...)</dt><dd><tt>Returns&nbsp;a&nbsp;md5&nbsp;hash&nbsp;<a href="__builtin__.html#object">object</a>;&nbsp;optionally&nbsp;initialized&nbsp;with&nbsp;a&nbsp;string</tt></dd></dl> </td></tr></table><p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#55aa55"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr> <tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%"><strong>ACCESS_TOKEN_URL</strong> = 'https://api.twitter.com/oauth/access_token'<br> <strong>AUTHORIZATION_URL</strong> = 'https://api.twitter.com/oauth/authorize'<br> <strong>CHARACTER_LIMIT</strong> = 140<br> <strong>DEFAULT_CACHE</strong> = &lt;object object at 0x1001da0a0&gt;<br> <strong>REQUEST_TOKEN_URL</strong> = 'https://api.twitter.com/oauth/request_token'<br> <strong>SIGNIN_URL</strong> = 'https://api.twitter.com/oauth/authenticate'<br> <strong>__author__</strong> = 'python-twitter@googlegroups.com'<br> <strong>__version__</strong> = '0.8'</td></tr></table><p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#7799ee"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr> <tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%">python-twitter@googlegroups.com</td></tr></table> </body></html>
123danielbenjaminphilpott-123
doc/twitter.html
HTML
asf20
132,276
#!/usr/bin/python2.4 # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''A library that provides a Python interface to the Twitter API''' __author__ = 'python-twitter@googlegroups.com' __version__ = '0.8.5' import calendar import datetime import httplib import os import rfc822 import sys import tempfile import textwrap import time import urllib import urllib2 import urlparse import gzip import StringIO try: # Python >= 2.6 import json as simplejson except ImportError: try: # Python < 2.6 import simplejson except ImportError: try: # Google App Engine from django.utils import simplejson except ImportError: raise ImportError, "Unable to load a json library" # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl, parse_qs except ImportError: from cgi import parse_qsl, parse_qs try: from hashlib import md5 except ImportError: from md5 import md5 import oauth2 as oauth CHARACTER_LIMIT = 140 # A singleton representing a lazily instantiated FileCache. DEFAULT_CACHE = object() REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' class TwitterError(Exception): '''Base class for Twitter errors''' @property def message(self): '''Returns the first argument used to construct this error.''' return self.args[0] class Status(object): '''A class representing the Status structure used by the twitter API. The Status structure exposes the following properties: status.created_at status.created_at_in_seconds # read only status.favorited status.in_reply_to_screen_name status.in_reply_to_user_id status.in_reply_to_status_id status.truncated status.source status.id status.text status.location status.relative_created_at # read only status.user status.urls status.user_mentions status.hashtags status.geo status.place status.coordinates status.contributors ''' def __init__(self, created_at=None, favorited=None, id=None, text=None, location=None, user=None, in_reply_to_screen_name=None, in_reply_to_user_id=None, in_reply_to_status_id=None, truncated=None, source=None, now=None, urls=None, user_mentions=None, hashtags=None, media=None, geo=None, place=None, coordinates=None, contributors=None, retweeted=None, retweeted_status=None, retweet_count=None): '''An object to hold a Twitter status message. This class is normally instantiated by the twitter.Api class and returned in a sequence. Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007" Args: created_at: The time this status message was posted. [Optional] favorited: Whether this is a favorite of the authenticated user. [Optional] id: The unique id of this status message. [Optional] text: The text of this status message. [Optional] location: the geolocation string associated with this message. [Optional] relative_created_at: A human readable string representing the posting time. [Optional] user: A twitter.User instance representing the person posting the message. [Optional] now: The current time, if the client chooses to set it. Defaults to the wall clock time. [Optional] urls: user_mentions: hashtags: geo: place: coordinates: contributors: retweeted: retweeted_status: retweet_count: ''' self.created_at = created_at self.favorited = favorited self.id = id self.text = text self.location = location self.user = user self.now = now self.in_reply_to_screen_name = in_reply_to_screen_name self.in_reply_to_user_id = in_reply_to_user_id self.in_reply_to_status_id = in_reply_to_status_id self.truncated = truncated self.retweeted = retweeted self.source = source self.urls = urls self.user_mentions = user_mentions self.hashtags = hashtags self.media = media self.geo = geo self.place = place self.coordinates = coordinates self.contributors = contributors self.retweeted_status = retweeted_status self.retweet_count = retweet_count def GetCreatedAt(self): '''Get the time this status message was posted. Returns: The time this status message was posted ''' return self._created_at def SetCreatedAt(self, created_at): '''Set the time this status message was posted. Args: created_at: The time this status message was created ''' self._created_at = created_at created_at = property(GetCreatedAt, SetCreatedAt, doc='The time this status message was posted.') def GetCreatedAtInSeconds(self): '''Get the time this status message was posted, in seconds since the epoch. Returns: The time this status message was posted, in seconds since the epoch. ''' return calendar.timegm(rfc822.parsedate(self.created_at)) created_at_in_seconds = property(GetCreatedAtInSeconds, doc="The time this status message was " "posted, in seconds since the epoch") def GetFavorited(self): '''Get the favorited setting of this status message. Returns: True if this status message is favorited; False otherwise ''' return self._favorited def SetFavorited(self, favorited): '''Set the favorited state of this status message. Args: favorited: boolean True/False favorited state of this status message ''' self._favorited = favorited favorited = property(GetFavorited, SetFavorited, doc='The favorited state of this status message.') def GetId(self): '''Get the unique id of this status message. Returns: The unique id of this status message ''' return self._id def SetId(self, id): '''Set the unique id of this status message. Args: id: The unique id of this status message ''' self._id = id id = property(GetId, SetId, doc='The unique id of this status message.') def GetInReplyToScreenName(self): return self._in_reply_to_screen_name def SetInReplyToScreenName(self, in_reply_to_screen_name): self._in_reply_to_screen_name = in_reply_to_screen_name in_reply_to_screen_name = property(GetInReplyToScreenName, SetInReplyToScreenName, doc='') def GetInReplyToUserId(self): return self._in_reply_to_user_id def SetInReplyToUserId(self, in_reply_to_user_id): self._in_reply_to_user_id = in_reply_to_user_id in_reply_to_user_id = property(GetInReplyToUserId, SetInReplyToUserId, doc='') def GetInReplyToStatusId(self): return self._in_reply_to_status_id def SetInReplyToStatusId(self, in_reply_to_status_id): self._in_reply_to_status_id = in_reply_to_status_id in_reply_to_status_id = property(GetInReplyToStatusId, SetInReplyToStatusId, doc='') def GetTruncated(self): return self._truncated def SetTruncated(self, truncated): self._truncated = truncated truncated = property(GetTruncated, SetTruncated, doc='') def GetRetweeted(self): return self._retweeted def SetRetweeted(self, retweeted): self._retweeted = retweeted retweeted = property(GetRetweeted, SetRetweeted, doc='') def GetSource(self): return self._source def SetSource(self, source): self._source = source source = property(GetSource, SetSource, doc='') def GetText(self): '''Get the text of this status message. Returns: The text of this status message. ''' return self._text def SetText(self, text): '''Set the text of this status message. Args: text: The text of this status message ''' self._text = text text = property(GetText, SetText, doc='The text of this status message') def GetLocation(self): '''Get the geolocation associated with this status message Returns: The geolocation string of this status message. ''' return self._location def SetLocation(self, location): '''Set the geolocation associated with this status message Args: location: The geolocation string of this status message ''' self._location = location location = property(GetLocation, SetLocation, doc='The geolocation string of this status message') def GetRelativeCreatedAt(self): '''Get a human readable string representing the posting time Returns: A human readable string representing the posting time ''' fudge = 1.25 delta = long(self.now) - long(self.created_at_in_seconds) if delta < (1 * fudge): return 'about a second ago' elif delta < (60 * (1/fudge)): return 'about %d seconds ago' % (delta) elif delta < (60 * fudge): return 'about a minute ago' elif delta < (60 * 60 * (1/fudge)): return 'about %d minutes ago' % (delta / 60) elif delta < (60 * 60 * fudge) or delta / (60 * 60) == 1: return 'about an hour ago' elif delta < (60 * 60 * 24 * (1/fudge)): return 'about %d hours ago' % (delta / (60 * 60)) elif delta < (60 * 60 * 24 * fudge) or delta / (60 * 60 * 24) == 1: return 'about a day ago' else: return 'about %d days ago' % (delta / (60 * 60 * 24)) relative_created_at = property(GetRelativeCreatedAt, doc='Get a human readable string representing ' 'the posting time') def GetUser(self): '''Get a twitter.User representing the entity posting this status message. Returns: A twitter.User representing the entity posting this status message ''' return self._user def SetUser(self, user): '''Set a twitter.User representing the entity posting this status message. Args: user: A twitter.User representing the entity posting this status message ''' self._user = user user = property(GetUser, SetUser, doc='A twitter.User representing the entity posting this ' 'status message') def GetNow(self): '''Get the wallclock time for this status message. Used to calculate relative_created_at. Defaults to the time the object was instantiated. Returns: Whatever the status instance believes the current time to be, in seconds since the epoch. ''' if self._now is None: self._now = time.time() return self._now def SetNow(self, now): '''Set the wallclock time for this status message. Used to calculate relative_created_at. Defaults to the time the object was instantiated. Args: now: The wallclock time for this instance. ''' self._now = now now = property(GetNow, SetNow, doc='The wallclock time for this status instance.') def GetGeo(self): return self._geo def SetGeo(self, geo): self._geo = geo geo = property(GetGeo, SetGeo, doc='') def GetPlace(self): return self._place def SetPlace(self, place): self._place = place place = property(GetPlace, SetPlace, doc='') def GetCoordinates(self): return self._coordinates def SetCoordinates(self, coordinates): self._coordinates = coordinates coordinates = property(GetCoordinates, SetCoordinates, doc='') def GetContributors(self): return self._contributors def SetContributors(self, contributors): self._contributors = contributors contributors = property(GetContributors, SetContributors, doc='') def GetRetweeted_status(self): return self._retweeted_status def SetRetweeted_status(self, retweeted_status): self._retweeted_status = retweeted_status retweeted_status = property(GetRetweeted_status, SetRetweeted_status, doc='') def GetRetweetCount(self): return self._retweet_count def SetRetweetCount(self, retweet_count): self._retweet_count = retweet_count retweet_count = property(GetRetweetCount, SetRetweetCount, doc='') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.created_at == other.created_at and \ self.id == other.id and \ self.text == other.text and \ self.location == other.location and \ self.user == other.user and \ self.in_reply_to_screen_name == other.in_reply_to_screen_name and \ self.in_reply_to_user_id == other.in_reply_to_user_id and \ self.in_reply_to_status_id == other.in_reply_to_status_id and \ self.truncated == other.truncated and \ self.retweeted == other.retweeted and \ self.favorited == other.favorited and \ self.source == other.source and \ self.geo == other.geo and \ self.place == other.place and \ self.coordinates == other.coordinates and \ self.contributors == other.contributors and \ self.retweeted_status == other.retweeted_status and \ self.retweet_count == other.retweet_count except AttributeError: return False def __str__(self): '''A string representation of this twitter.Status instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.Status instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.Status instance. Returns: A JSON string representation of this twitter.Status instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.Status instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.Status instance ''' data = {} if self.created_at: data['created_at'] = self.created_at if self.favorited: data['favorited'] = self.favorited if self.id: data['id'] = self.id if self.text: data['text'] = self.text if self.location: data['location'] = self.location if self.user: data['user'] = self.user.AsDict() if self.in_reply_to_screen_name: data['in_reply_to_screen_name'] = self.in_reply_to_screen_name if self.in_reply_to_user_id: data['in_reply_to_user_id'] = self.in_reply_to_user_id if self.in_reply_to_status_id: data['in_reply_to_status_id'] = self.in_reply_to_status_id if self.truncated is not None: data['truncated'] = self.truncated if self.retweeted is not None: data['retweeted'] = self.retweeted if self.favorited is not None: data['favorited'] = self.favorited if self.source: data['source'] = self.source if self.geo: data['geo'] = self.geo if self.place: data['place'] = self.place if self.coordinates: data['coordinates'] = self.coordinates if self.contributors: data['contributors'] = self.contributors if self.hashtags: data['hashtags'] = [h.text for h in self.hashtags] if self.retweeted_status: data['retweeted_status'] = self.retweeted_status.AsDict() if self.retweet_count: data['retweet_count'] = self.retweet_count if self.urls: data['urls'] = dict([(url.url, url.expanded_url) for url in self.urls]) if self.user_mentions: data['user_mentions'] = [um.AsDict() for um in self.user_mentions] return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.Status instance ''' if 'user' in data: user = User.NewFromJsonDict(data['user']) else: user = None if 'retweeted_status' in data: retweeted_status = Status.NewFromJsonDict(data['retweeted_status']) else: retweeted_status = None urls = None user_mentions = None hashtags = None media = None if 'entities' in data: if 'urls' in data['entities']: urls = [Url.NewFromJsonDict(u) for u in data['entities']['urls']] if 'user_mentions' in data['entities']: user_mentions = [User.NewFromJsonDict(u) for u in data['entities']['user_mentions']] if 'hashtags' in data['entities']: hashtags = [Hashtag.NewFromJsonDict(h) for h in data['entities']['hashtags']] if 'media' in data['entities']: media = data['entities']['media'] else: media = [] return Status(created_at=data.get('created_at', None), favorited=data.get('favorited', None), id=data.get('id', None), text=data.get('text', None), location=data.get('location', None), in_reply_to_screen_name=data.get('in_reply_to_screen_name', None), in_reply_to_user_id=data.get('in_reply_to_user_id', None), in_reply_to_status_id=data.get('in_reply_to_status_id', None), truncated=data.get('truncated', None), retweeted=data.get('retweeted', None), source=data.get('source', None), user=user, urls=urls, user_mentions=user_mentions, hashtags=hashtags, media=media, geo=data.get('geo', None), place=data.get('place', None), coordinates=data.get('coordinates', None), contributors=data.get('contributors', None), retweeted_status=retweeted_status, retweet_count=data.get('retweet_count', None)) class User(object): '''A class representing the User structure used by the twitter API. The User structure exposes the following properties: user.id user.name user.screen_name user.location user.description user.profile_image_url user.profile_background_tile user.profile_background_image_url user.profile_sidebar_fill_color user.profile_background_color user.profile_link_color user.profile_text_color user.protected user.utc_offset user.time_zone user.url user.status user.statuses_count user.followers_count user.friends_count user.favourites_count user.geo_enabled user.verified user.lang user.notifications user.contributors_enabled user.created_at user.listed_count ''' def __init__(self, id=None, name=None, screen_name=None, location=None, description=None, profile_image_url=None, profile_background_tile=None, profile_background_image_url=None, profile_sidebar_fill_color=None, profile_background_color=None, profile_link_color=None, profile_text_color=None, protected=None, utc_offset=None, time_zone=None, followers_count=None, friends_count=None, statuses_count=None, favourites_count=None, url=None, status=None, geo_enabled=None, verified=None, lang=None, notifications=None, contributors_enabled=None, created_at=None, listed_count=None): self.id = id self.name = name self.screen_name = screen_name self.location = location self.description = description self.profile_image_url = profile_image_url self.profile_background_tile = profile_background_tile self.profile_background_image_url = profile_background_image_url self.profile_sidebar_fill_color = profile_sidebar_fill_color self.profile_background_color = profile_background_color self.profile_link_color = profile_link_color self.profile_text_color = profile_text_color self.protected = protected self.utc_offset = utc_offset self.time_zone = time_zone self.followers_count = followers_count self.friends_count = friends_count self.statuses_count = statuses_count self.favourites_count = favourites_count self.url = url self.status = status self.geo_enabled = geo_enabled self.verified = verified self.lang = lang self.notifications = notifications self.contributors_enabled = contributors_enabled self.created_at = created_at self.listed_count = listed_count def GetId(self): '''Get the unique id of this user. Returns: The unique id of this user ''' return self._id def SetId(self, id): '''Set the unique id of this user. Args: id: The unique id of this user. ''' self._id = id id = property(GetId, SetId, doc='The unique id of this user.') def GetName(self): '''Get the real name of this user. Returns: The real name of this user ''' return self._name def SetName(self, name): '''Set the real name of this user. Args: name: The real name of this user ''' self._name = name name = property(GetName, SetName, doc='The real name of this user.') def GetScreenName(self): '''Get the short twitter name of this user. Returns: The short twitter name of this user ''' return self._screen_name def SetScreenName(self, screen_name): '''Set the short twitter name of this user. Args: screen_name: the short twitter name of this user ''' self._screen_name = screen_name screen_name = property(GetScreenName, SetScreenName, doc='The short twitter name of this user.') def GetLocation(self): '''Get the geographic location of this user. Returns: The geographic location of this user ''' return self._location def SetLocation(self, location): '''Set the geographic location of this user. Args: location: The geographic location of this user ''' self._location = location location = property(GetLocation, SetLocation, doc='The geographic location of this user.') def GetDescription(self): '''Get the short text description of this user. Returns: The short text description of this user ''' return self._description def SetDescription(self, description): '''Set the short text description of this user. Args: description: The short text description of this user ''' self._description = description description = property(GetDescription, SetDescription, doc='The short text description of this user.') def GetUrl(self): '''Get the homepage url of this user. Returns: The homepage url of this user ''' return self._url def SetUrl(self, url): '''Set the homepage url of this user. Args: url: The homepage url of this user ''' self._url = url url = property(GetUrl, SetUrl, doc='The homepage url of this user.') def GetProfileImageUrl(self): '''Get the url of the thumbnail of this user. Returns: The url of the thumbnail of this user ''' return self._profile_image_url def SetProfileImageUrl(self, profile_image_url): '''Set the url of the thumbnail of this user. Args: profile_image_url: The url of the thumbnail of this user ''' self._profile_image_url = profile_image_url profile_image_url= property(GetProfileImageUrl, SetProfileImageUrl, doc='The url of the thumbnail of this user.') def GetProfileBackgroundTile(self): '''Boolean for whether to tile the profile background image. Returns: True if the background is to be tiled, False if not, None if unset. ''' return self._profile_background_tile def SetProfileBackgroundTile(self, profile_background_tile): '''Set the boolean flag for whether to tile the profile background image. Args: profile_background_tile: Boolean flag for whether to tile or not. ''' self._profile_background_tile = profile_background_tile profile_background_tile = property(GetProfileBackgroundTile, SetProfileBackgroundTile, doc='Boolean for whether to tile the background image.') def GetProfileBackgroundImageUrl(self): return self._profile_background_image_url def SetProfileBackgroundImageUrl(self, profile_background_image_url): self._profile_background_image_url = profile_background_image_url profile_background_image_url = property(GetProfileBackgroundImageUrl, SetProfileBackgroundImageUrl, doc='The url of the profile background of this user.') def GetProfileSidebarFillColor(self): return self._profile_sidebar_fill_color def SetProfileSidebarFillColor(self, profile_sidebar_fill_color): self._profile_sidebar_fill_color = profile_sidebar_fill_color profile_sidebar_fill_color = property(GetProfileSidebarFillColor, SetProfileSidebarFillColor) def GetProfileBackgroundColor(self): return self._profile_background_color def SetProfileBackgroundColor(self, profile_background_color): self._profile_background_color = profile_background_color profile_background_color = property(GetProfileBackgroundColor, SetProfileBackgroundColor) def GetProfileLinkColor(self): return self._profile_link_color def SetProfileLinkColor(self, profile_link_color): self._profile_link_color = profile_link_color profile_link_color = property(GetProfileLinkColor, SetProfileLinkColor) def GetProfileTextColor(self): return self._profile_text_color def SetProfileTextColor(self, profile_text_color): self._profile_text_color = profile_text_color profile_text_color = property(GetProfileTextColor, SetProfileTextColor) def GetProtected(self): return self._protected def SetProtected(self, protected): self._protected = protected protected = property(GetProtected, SetProtected) def GetUtcOffset(self): return self._utc_offset def SetUtcOffset(self, utc_offset): self._utc_offset = utc_offset utc_offset = property(GetUtcOffset, SetUtcOffset) def GetTimeZone(self): '''Returns the current time zone string for the user. Returns: The descriptive time zone string for the user. ''' return self._time_zone def SetTimeZone(self, time_zone): '''Sets the user's time zone string. Args: time_zone: The descriptive time zone to assign for the user. ''' self._time_zone = time_zone time_zone = property(GetTimeZone, SetTimeZone) def GetStatus(self): '''Get the latest twitter.Status of this user. Returns: The latest twitter.Status of this user ''' return self._status def SetStatus(self, status): '''Set the latest twitter.Status of this user. Args: status: The latest twitter.Status of this user ''' self._status = status status = property(GetStatus, SetStatus, doc='The latest twitter.Status of this user.') def GetFriendsCount(self): '''Get the friend count for this user. Returns: The number of users this user has befriended. ''' return self._friends_count def SetFriendsCount(self, count): '''Set the friend count for this user. Args: count: The number of users this user has befriended. ''' self._friends_count = count friends_count = property(GetFriendsCount, SetFriendsCount, doc='The number of friends for this user.') def GetListedCount(self): '''Get the listed count for this user. Returns: The number of lists this user belongs to. ''' return self._listed_count def SetListedCount(self, count): '''Set the listed count for this user. Args: count: The number of lists this user belongs to. ''' self._listed_count = count listed_count = property(GetListedCount, SetListedCount, doc='The number of lists this user belongs to.') def GetFollowersCount(self): '''Get the follower count for this user. Returns: The number of users following this user. ''' return self._followers_count def SetFollowersCount(self, count): '''Set the follower count for this user. Args: count: The number of users following this user. ''' self._followers_count = count followers_count = property(GetFollowersCount, SetFollowersCount, doc='The number of users following this user.') def GetStatusesCount(self): '''Get the number of status updates for this user. Returns: The number of status updates for this user. ''' return self._statuses_count def SetStatusesCount(self, count): '''Set the status update count for this user. Args: count: The number of updates for this user. ''' self._statuses_count = count statuses_count = property(GetStatusesCount, SetStatusesCount, doc='The number of updates for this user.') def GetFavouritesCount(self): '''Get the number of favourites for this user. Returns: The number of favourites for this user. ''' return self._favourites_count def SetFavouritesCount(self, count): '''Set the favourite count for this user. Args: count: The number of favourites for this user. ''' self._favourites_count = count favourites_count = property(GetFavouritesCount, SetFavouritesCount, doc='The number of favourites for this user.') def GetGeoEnabled(self): '''Get the setting of geo_enabled for this user. Returns: True/False if Geo tagging is enabled ''' return self._geo_enabled def SetGeoEnabled(self, geo_enabled): '''Set the latest twitter.geo_enabled of this user. Args: geo_enabled: True/False if Geo tagging is to be enabled ''' self._geo_enabled = geo_enabled geo_enabled = property(GetGeoEnabled, SetGeoEnabled, doc='The value of twitter.geo_enabled for this user.') def GetVerified(self): '''Get the setting of verified for this user. Returns: True/False if user is a verified account ''' return self._verified def SetVerified(self, verified): '''Set twitter.verified for this user. Args: verified: True/False if user is a verified account ''' self._verified = verified verified = property(GetVerified, SetVerified, doc='The value of twitter.verified for this user.') def GetLang(self): '''Get the setting of lang for this user. Returns: language code of the user ''' return self._lang def SetLang(self, lang): '''Set twitter.lang for this user. Args: lang: language code for the user ''' self._lang = lang lang = property(GetLang, SetLang, doc='The value of twitter.lang for this user.') def GetNotifications(self): '''Get the setting of notifications for this user. Returns: True/False for the notifications setting of the user ''' return self._notifications def SetNotifications(self, notifications): '''Set twitter.notifications for this user. Args: notifications: True/False notifications setting for the user ''' self._notifications = notifications notifications = property(GetNotifications, SetNotifications, doc='The value of twitter.notifications for this user.') def GetContributorsEnabled(self): '''Get the setting of contributors_enabled for this user. Returns: True/False contributors_enabled of the user ''' return self._contributors_enabled def SetContributorsEnabled(self, contributors_enabled): '''Set twitter.contributors_enabled for this user. Args: contributors_enabled: True/False contributors_enabled setting for the user ''' self._contributors_enabled = contributors_enabled contributors_enabled = property(GetContributorsEnabled, SetContributorsEnabled, doc='The value of twitter.contributors_enabled for this user.') def GetCreatedAt(self): '''Get the setting of created_at for this user. Returns: created_at value of the user ''' return self._created_at def SetCreatedAt(self, created_at): '''Set twitter.created_at for this user. Args: created_at: created_at value for the user ''' self._created_at = created_at created_at = property(GetCreatedAt, SetCreatedAt, doc='The value of twitter.created_at for this user.') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.id == other.id and \ self.name == other.name and \ self.screen_name == other.screen_name and \ self.location == other.location and \ self.description == other.description and \ self.profile_image_url == other.profile_image_url and \ self.profile_background_tile == other.profile_background_tile and \ self.profile_background_image_url == other.profile_background_image_url and \ self.profile_sidebar_fill_color == other.profile_sidebar_fill_color and \ self.profile_background_color == other.profile_background_color and \ self.profile_link_color == other.profile_link_color and \ self.profile_text_color == other.profile_text_color and \ self.protected == other.protected and \ self.utc_offset == other.utc_offset and \ self.time_zone == other.time_zone and \ self.url == other.url and \ self.statuses_count == other.statuses_count and \ self.followers_count == other.followers_count and \ self.favourites_count == other.favourites_count and \ self.friends_count == other.friends_count and \ self.status == other.status and \ self.geo_enabled == other.geo_enabled and \ self.verified == other.verified and \ self.lang == other.lang and \ self.notifications == other.notifications and \ self.contributors_enabled == other.contributors_enabled and \ self.created_at == other.created_at and \ self.listed_count == other.listed_count except AttributeError: return False def __str__(self): '''A string representation of this twitter.User instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.User instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.User instance. Returns: A JSON string representation of this twitter.User instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.User instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.User instance ''' data = {} if self.id: data['id'] = self.id if self.name: data['name'] = self.name if self.screen_name: data['screen_name'] = self.screen_name if self.location: data['location'] = self.location if self.description: data['description'] = self.description if self.profile_image_url: data['profile_image_url'] = self.profile_image_url if self.profile_background_tile is not None: data['profile_background_tile'] = self.profile_background_tile if self.profile_background_image_url: data['profile_sidebar_fill_color'] = self.profile_background_image_url if self.profile_background_color: data['profile_background_color'] = self.profile_background_color if self.profile_link_color: data['profile_link_color'] = self.profile_link_color if self.profile_text_color: data['profile_text_color'] = self.profile_text_color if self.protected is not None: data['protected'] = self.protected if self.utc_offset: data['utc_offset'] = self.utc_offset if self.time_zone: data['time_zone'] = self.time_zone if self.url: data['url'] = self.url if self.status: data['status'] = self.status.AsDict() if self.friends_count: data['friends_count'] = self.friends_count if self.followers_count: data['followers_count'] = self.followers_count if self.statuses_count: data['statuses_count'] = self.statuses_count if self.favourites_count: data['favourites_count'] = self.favourites_count if self.geo_enabled: data['geo_enabled'] = self.geo_enabled if self.verified: data['verified'] = self.verified if self.lang: data['lang'] = self.lang if self.notifications: data['notifications'] = self.notifications if self.contributors_enabled: data['contributors_enabled'] = self.contributors_enabled if self.created_at: data['created_at'] = self.created_at if self.listed_count: data['listed_count'] = self.listed_count return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.User instance ''' if 'status' in data: status = Status.NewFromJsonDict(data['status']) else: status = None return User(id=data.get('id', None), name=data.get('name', None), screen_name=data.get('screen_name', None), location=data.get('location', None), description=data.get('description', None), statuses_count=data.get('statuses_count', None), followers_count=data.get('followers_count', None), favourites_count=data.get('favourites_count', None), friends_count=data.get('friends_count', None), profile_image_url=data.get('profile_image_url', None), profile_background_tile = data.get('profile_background_tile', None), profile_background_image_url = data.get('profile_background_image_url', None), profile_sidebar_fill_color = data.get('profile_sidebar_fill_color', None), profile_background_color = data.get('profile_background_color', None), profile_link_color = data.get('profile_link_color', None), profile_text_color = data.get('profile_text_color', None), protected = data.get('protected', None), utc_offset = data.get('utc_offset', None), time_zone = data.get('time_zone', None), url=data.get('url', None), status=status, geo_enabled=data.get('geo_enabled', None), verified=data.get('verified', None), lang=data.get('lang', None), notifications=data.get('notifications', None), contributors_enabled=data.get('contributors_enabled', None), created_at=data.get('created_at', None), listed_count=data.get('listed_count', None)) class List(object): '''A class representing the List structure used by the twitter API. The List structure exposes the following properties: list.id list.name list.slug list.description list.full_name list.mode list.uri list.member_count list.subscriber_count list.following ''' def __init__(self, id=None, name=None, slug=None, description=None, full_name=None, mode=None, uri=None, member_count=None, subscriber_count=None, following=None, user=None): self.id = id self.name = name self.slug = slug self.description = description self.full_name = full_name self.mode = mode self.uri = uri self.member_count = member_count self.subscriber_count = subscriber_count self.following = following self.user = user def GetId(self): '''Get the unique id of this list. Returns: The unique id of this list ''' return self._id def SetId(self, id): '''Set the unique id of this list. Args: id: The unique id of this list. ''' self._id = id id = property(GetId, SetId, doc='The unique id of this list.') def GetName(self): '''Get the real name of this list. Returns: The real name of this list ''' return self._name def SetName(self, name): '''Set the real name of this list. Args: name: The real name of this list ''' self._name = name name = property(GetName, SetName, doc='The real name of this list.') def GetSlug(self): '''Get the slug of this list. Returns: The slug of this list ''' return self._slug def SetSlug(self, slug): '''Set the slug of this list. Args: slug: The slug of this list. ''' self._slug = slug slug = property(GetSlug, SetSlug, doc='The slug of this list.') def GetDescription(self): '''Get the description of this list. Returns: The description of this list ''' return self._description def SetDescription(self, description): '''Set the description of this list. Args: description: The description of this list. ''' self._description = description description = property(GetDescription, SetDescription, doc='The description of this list.') def GetFull_name(self): '''Get the full_name of this list. Returns: The full_name of this list ''' return self._full_name def SetFull_name(self, full_name): '''Set the full_name of this list. Args: full_name: The full_name of this list. ''' self._full_name = full_name full_name = property(GetFull_name, SetFull_name, doc='The full_name of this list.') def GetMode(self): '''Get the mode of this list. Returns: The mode of this list ''' return self._mode def SetMode(self, mode): '''Set the mode of this list. Args: mode: The mode of this list. ''' self._mode = mode mode = property(GetMode, SetMode, doc='The mode of this list.') def GetUri(self): '''Get the uri of this list. Returns: The uri of this list ''' return self._uri def SetUri(self, uri): '''Set the uri of this list. Args: uri: The uri of this list. ''' self._uri = uri uri = property(GetUri, SetUri, doc='The uri of this list.') def GetMember_count(self): '''Get the member_count of this list. Returns: The member_count of this list ''' return self._member_count def SetMember_count(self, member_count): '''Set the member_count of this list. Args: member_count: The member_count of this list. ''' self._member_count = member_count member_count = property(GetMember_count, SetMember_count, doc='The member_count of this list.') def GetSubscriber_count(self): '''Get the subscriber_count of this list. Returns: The subscriber_count of this list ''' return self._subscriber_count def SetSubscriber_count(self, subscriber_count): '''Set the subscriber_count of this list. Args: subscriber_count: The subscriber_count of this list. ''' self._subscriber_count = subscriber_count subscriber_count = property(GetSubscriber_count, SetSubscriber_count, doc='The subscriber_count of this list.') def GetFollowing(self): '''Get the following status of this list. Returns: The following status of this list ''' return self._following def SetFollowing(self, following): '''Set the following status of this list. Args: following: The following of this list. ''' self._following = following following = property(GetFollowing, SetFollowing, doc='The following status of this list.') def GetUser(self): '''Get the user of this list. Returns: The owner of this list ''' return self._user def SetUser(self, user): '''Set the user of this list. Args: user: The owner of this list. ''' self._user = user user = property(GetUser, SetUser, doc='The owner of this list.') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.id == other.id and \ self.name == other.name and \ self.slug == other.slug and \ self.description == other.description and \ self.full_name == other.full_name and \ self.mode == other.mode and \ self.uri == other.uri and \ self.member_count == other.member_count and \ self.subscriber_count == other.subscriber_count and \ self.following == other.following and \ self.user == other.user except AttributeError: return False def __str__(self): '''A string representation of this twitter.List instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.List instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.List instance. Returns: A JSON string representation of this twitter.List instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.List instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.List instance ''' data = {} if self.id: data['id'] = self.id if self.name: data['name'] = self.name if self.slug: data['slug'] = self.slug if self.description: data['description'] = self.description if self.full_name: data['full_name'] = self.full_name if self.mode: data['mode'] = self.mode if self.uri: data['uri'] = self.uri if self.member_count is not None: data['member_count'] = self.member_count if self.subscriber_count is not None: data['subscriber_count'] = self.subscriber_count if self.following is not None: data['following'] = self.following if self.user is not None: data['user'] = self.user return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.List instance ''' if 'user' in data: user = User.NewFromJsonDict(data['user']) else: user = None return List(id=data.get('id', None), name=data.get('name', None), slug=data.get('slug', None), description=data.get('description', None), full_name=data.get('full_name', None), mode=data.get('mode', None), uri=data.get('uri', None), member_count=data.get('member_count', None), subscriber_count=data.get('subscriber_count', None), following=data.get('following', None), user=user) class DirectMessage(object): '''A class representing the DirectMessage structure used by the twitter API. The DirectMessage structure exposes the following properties: direct_message.id direct_message.created_at direct_message.created_at_in_seconds # read only direct_message.sender_id direct_message.sender_screen_name direct_message.recipient_id direct_message.recipient_screen_name direct_message.text ''' def __init__(self, id=None, created_at=None, sender_id=None, sender_screen_name=None, recipient_id=None, recipient_screen_name=None, text=None): '''An object to hold a Twitter direct message. This class is normally instantiated by the twitter.Api class and returned in a sequence. Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007" Args: id: The unique id of this direct message. [Optional] created_at: The time this direct message was posted. [Optional] sender_id: The id of the twitter user that sent this message. [Optional] sender_screen_name: The name of the twitter user that sent this message. [Optional] recipient_id: The id of the twitter that received this message. [Optional] recipient_screen_name: The name of the twitter that received this message. [Optional] text: The text of this direct message. [Optional] ''' self.id = id self.created_at = created_at self.sender_id = sender_id self.sender_screen_name = sender_screen_name self.recipient_id = recipient_id self.recipient_screen_name = recipient_screen_name self.text = text def GetId(self): '''Get the unique id of this direct message. Returns: The unique id of this direct message ''' return self._id def SetId(self, id): '''Set the unique id of this direct message. Args: id: The unique id of this direct message ''' self._id = id id = property(GetId, SetId, doc='The unique id of this direct message.') def GetCreatedAt(self): '''Get the time this direct message was posted. Returns: The time this direct message was posted ''' return self._created_at def SetCreatedAt(self, created_at): '''Set the time this direct message was posted. Args: created_at: The time this direct message was created ''' self._created_at = created_at created_at = property(GetCreatedAt, SetCreatedAt, doc='The time this direct message was posted.') def GetCreatedAtInSeconds(self): '''Get the time this direct message was posted, in seconds since the epoch. Returns: The time this direct message was posted, in seconds since the epoch. ''' return calendar.timegm(rfc822.parsedate(self.created_at)) created_at_in_seconds = property(GetCreatedAtInSeconds, doc="The time this direct message was " "posted, in seconds since the epoch") def GetSenderId(self): '''Get the unique sender id of this direct message. Returns: The unique sender id of this direct message ''' return self._sender_id def SetSenderId(self, sender_id): '''Set the unique sender id of this direct message. Args: sender_id: The unique sender id of this direct message ''' self._sender_id = sender_id sender_id = property(GetSenderId, SetSenderId, doc='The unique sender id of this direct message.') def GetSenderScreenName(self): '''Get the unique sender screen name of this direct message. Returns: The unique sender screen name of this direct message ''' return self._sender_screen_name def SetSenderScreenName(self, sender_screen_name): '''Set the unique sender screen name of this direct message. Args: sender_screen_name: The unique sender screen name of this direct message ''' self._sender_screen_name = sender_screen_name sender_screen_name = property(GetSenderScreenName, SetSenderScreenName, doc='The unique sender screen name of this direct message.') def GetRecipientId(self): '''Get the unique recipient id of this direct message. Returns: The unique recipient id of this direct message ''' return self._recipient_id def SetRecipientId(self, recipient_id): '''Set the unique recipient id of this direct message. Args: recipient_id: The unique recipient id of this direct message ''' self._recipient_id = recipient_id recipient_id = property(GetRecipientId, SetRecipientId, doc='The unique recipient id of this direct message.') def GetRecipientScreenName(self): '''Get the unique recipient screen name of this direct message. Returns: The unique recipient screen name of this direct message ''' return self._recipient_screen_name def SetRecipientScreenName(self, recipient_screen_name): '''Set the unique recipient screen name of this direct message. Args: recipient_screen_name: The unique recipient screen name of this direct message ''' self._recipient_screen_name = recipient_screen_name recipient_screen_name = property(GetRecipientScreenName, SetRecipientScreenName, doc='The unique recipient screen name of this direct message.') def GetText(self): '''Get the text of this direct message. Returns: The text of this direct message. ''' return self._text def SetText(self, text): '''Set the text of this direct message. Args: text: The text of this direct message ''' self._text = text text = property(GetText, SetText, doc='The text of this direct message') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.id == other.id and \ self.created_at == other.created_at and \ self.sender_id == other.sender_id and \ self.sender_screen_name == other.sender_screen_name and \ self.recipient_id == other.recipient_id and \ self.recipient_screen_name == other.recipient_screen_name and \ self.text == other.text except AttributeError: return False def __str__(self): '''A string representation of this twitter.DirectMessage instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.DirectMessage instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.DirectMessage instance. Returns: A JSON string representation of this twitter.DirectMessage instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.DirectMessage instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.DirectMessage instance ''' data = {} if self.id: data['id'] = self.id if self.created_at: data['created_at'] = self.created_at if self.sender_id: data['sender_id'] = self.sender_id if self.sender_screen_name: data['sender_screen_name'] = self.sender_screen_name if self.recipient_id: data['recipient_id'] = self.recipient_id if self.recipient_screen_name: data['recipient_screen_name'] = self.recipient_screen_name if self.text: data['text'] = self.text return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.DirectMessage instance ''' return DirectMessage(created_at=data.get('created_at', None), recipient_id=data.get('recipient_id', None), sender_id=data.get('sender_id', None), text=data.get('text', None), sender_screen_name=data.get('sender_screen_name', None), id=data.get('id', None), recipient_screen_name=data.get('recipient_screen_name', None)) class Hashtag(object): ''' A class representing a twitter hashtag ''' def __init__(self, text=None): self.text = text @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.Hashtag instance ''' return Hashtag(text = data.get('text', None)) class Trend(object): ''' A class representing a trending topic ''' def __init__(self, name=None, query=None, timestamp=None): self.name = name self.query = query self.timestamp = timestamp def __str__(self): return 'Name: %s\nQuery: %s\nTimestamp: %s\n' % (self.name, self.query, self.timestamp) def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.name == other.name and \ self.query == other.query and \ self.timestamp == other.timestamp except AttributeError: return False @staticmethod def NewFromJsonDict(data, timestamp = None): '''Create a new instance based on a JSON dict Args: data: A JSON dict timestamp: Gets set as the timestamp property of the new object Returns: A twitter.Trend object ''' return Trend(name=data.get('name', None), query=data.get('query', None), timestamp=timestamp) class Url(object): '''A class representing an URL contained in a tweet''' def __init__(self, url=None, expanded_url=None): self.url = url self.expanded_url = expanded_url @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.Url instance ''' return Url(url=data.get('url', None), expanded_url=data.get('expanded_url', None)) class Api(object): '''A python interface into the Twitter API By default, the Api caches results for 1 minute. Example usage: To create an instance of the twitter.Api class, with no authentication: >>> import twitter >>> api = twitter.Api() To fetch the most recently posted public twitter status messages: >>> statuses = api.GetPublicTimeline() >>> print [s.user.name for s in statuses] [u'DeWitt', u'Kesuke Miyagi', u'ev', u'Buzz Andersen', u'Biz Stone'] #... To fetch a single user's public status messages, where "user" is either a Twitter "short name" or their user id. >>> statuses = api.GetUserTimeline(user) >>> print [s.text for s in statuses] To use authentication, instantiate the twitter.Api class with a consumer key and secret; and the oAuth key and secret: >>> api = twitter.Api(consumer_key='twitter consumer key', consumer_secret='twitter consumer secret', access_token_key='the_key_given', access_token_secret='the_key_secret') To fetch your friends (after being authenticated): >>> users = api.GetFriends() >>> print [u.name for u in users] To post a twitter status message (after being authenticated): >>> status = api.PostUpdate('I love python-twitter!') >>> print status.text I love python-twitter! There are many other methods, including: >>> api.PostUpdates(status) >>> api.PostDirectMessage(user, text) >>> api.GetUser(user) >>> api.GetReplies() >>> api.GetUserTimeline(user) >>> api.GetStatus(id) >>> api.DestroyStatus(id) >>> api.GetFriendsTimeline(user) >>> api.GetFriends(user) >>> api.GetFollowers() >>> api.GetFeatured() >>> api.GetDirectMessages() >>> api.GetSentDirectMessages() >>> api.PostDirectMessage(user, text) >>> api.DestroyDirectMessage(id) >>> api.DestroyFriendship(user) >>> api.CreateFriendship(user) >>> api.GetUserByEmail(email) >>> api.VerifyCredentials() ''' DEFAULT_CACHE_TIMEOUT = 60 # cache for 1 minute _API_REALM = 'Twitter API' def __init__(self, consumer_key=None, consumer_secret=None, access_token_key=None, access_token_secret=None, input_encoding=None, request_headers=None, cache=DEFAULT_CACHE, shortner=None, base_url=None, use_gzip_compression=False, debugHTTP=False): '''Instantiate a new twitter.Api object. Args: consumer_key: Your Twitter user's consumer_key. consumer_secret: Your Twitter user's consumer_secret. access_token_key: The oAuth access token key value you retrieved from running get_access_token.py. access_token_secret: The oAuth access token's secret, also retrieved from the get_access_token.py run. input_encoding: The encoding used to encode input strings. [Optional] request_header: A dictionary of additional HTTP request headers. [Optional] cache: The cache instance to use. Defaults to DEFAULT_CACHE. Use None to disable caching. [Optional] shortner: The shortner instance to use. Defaults to None. See shorten_url.py for an example shortner. [Optional] base_url: The base URL to use to contact the Twitter API. Defaults to https://api.twitter.com. [Optional] use_gzip_compression: Set to True to tell enable gzip compression for any call made to Twitter. Defaults to False. [Optional] debugHTTP: Set to True to enable debug output from urllib2 when performing any HTTP requests. Defaults to False. [Optional] ''' self.SetCache(cache) self._urllib = urllib2 self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT self._input_encoding = input_encoding self._use_gzip = use_gzip_compression self._debugHTTP = debugHTTP self._oauth_consumer = None self._shortlink_size = 19 self._InitializeRequestHeaders(request_headers) self._InitializeUserAgent() self._InitializeDefaultParameters() if base_url is None: self.base_url = 'https://api.twitter.com/1' else: self.base_url = base_url if consumer_key is not None and (access_token_key is None or access_token_secret is None): print >> sys.stderr, 'Twitter now requires an oAuth Access Token for API calls.' print >> sys.stderr, 'If your using this library from a command line utility, please' print >> sys.stderr, 'run the the included get_access_token.py tool to generate one.' raise TwitterError('Twitter requires oAuth Access Token for all API access') self.SetCredentials(consumer_key, consumer_secret, access_token_key, access_token_secret) def SetCredentials(self, consumer_key, consumer_secret, access_token_key=None, access_token_secret=None): '''Set the consumer_key and consumer_secret for this instance Args: consumer_key: The consumer_key of the twitter account. consumer_secret: The consumer_secret for the twitter account. access_token_key: The oAuth access token key value you retrieved from running get_access_token.py. access_token_secret: The oAuth access token's secret, also retrieved from the get_access_token.py run. ''' self._consumer_key = consumer_key self._consumer_secret = consumer_secret self._access_token_key = access_token_key self._access_token_secret = access_token_secret self._oauth_consumer = None if consumer_key is not None and consumer_secret is not None and \ access_token_key is not None and access_token_secret is not None: self._signature_method_plaintext = oauth.SignatureMethod_PLAINTEXT() self._signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() self._oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret) self._oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) def ClearCredentials(self): '''Clear the any credentials for this instance ''' self._consumer_key = None self._consumer_secret = None self._access_token_key = None self._access_token_secret = None self._oauth_consumer = None def GetSearch(self, term=None, geocode=None, since_id=None, max_id=None, until=None, per_page=15, page=1, lang=None, show_user="true", result_type="mixed", include_entities=None, query_users=False): '''Return twitter search results for a given term. Args: term: term to search by. Optional if you include geocode. since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns only statuses with an ID less than (that is, older than) or equal to the specified ID. [Optional] until: Returns tweets generated before the given date. Date should be formatted as YYYY-MM-DD. [Optional] geocode: geolocation information in the form (latitude, longitude, radius) [Optional] per_page: number of results to return. Default is 15 [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] lang: language for results as ISO 639-1 code. Default is None (all languages) [Optional] show_user: prefixes screen name in status result_type: Type of result which should be returned. Default is "mixed". Other valid options are "recent" and "popular". [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] query_users: If set to False, then all users only have screen_name and profile_image_url available. If set to True, all information of users are available, but it uses lots of request quota, one per status. Returns: A sequence of twitter.Status instances, one for each message containing the term ''' # Build request parameters parameters = {} if since_id: try: parameters['since_id'] = long(since_id) except: raise TwitterError("since_id must be an integer") if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError("max_id must be an integer") if until: parameters['until'] = until if lang: parameters['lang'] = lang if term is None and geocode is None: return [] if term is not None: parameters['q'] = term if geocode is not None: parameters['geocode'] = ','.join(map(str, geocode)) if include_entities: parameters['include_entities'] = 1 parameters['show_user'] = show_user parameters['rpp'] = per_page parameters['page'] = page if result_type in ["mixed", "popular", "recent"]: parameters['result_type'] = result_type # Make and send requests url = 'http://search.twitter.com/search.json' json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) results = [] for x in data['results']: temp = Status.NewFromJsonDict(x) if query_users: # Build user object with new request temp.user = self.GetUser(urllib.quote(x['from_user'])) else: temp.user = User(screen_name=x['from_user'], profile_image_url=x['profile_image_url']) results.append(temp) # Return built list of statuses return results # [Status.NewFromJsonDict(x) for x in data['results']] def GetTrendsCurrent(self, exclude=None): '''Get the current top trending topics Args: exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with 10 entries. Each entry contains the twitter. ''' parameters = {} if exclude: parameters['exclude'] = exclude url = '%s/trends/current.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] for t in data['trends']: for item in data['trends'][t]: trends.append(Trend.NewFromJsonDict(item, timestamp = t)) return trends def GetTrendsWoeid(self, woeid, exclude=None): '''Return the top 10 trending topics for a specific WOEID, if trending information is available for it. Args: woeid: the Yahoo! Where On Earth ID for a location. exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with 10 entries. Each entry contains a Trend. ''' parameters = {} if exclude: parameters['exclude'] = exclude url = '%s/trends/%s.json' % (self.base_url, woeid) json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] timestamp = data[0]['as_of'] for trend in data[0]['trends']: trends.append(Trend.NewFromJsonDict(trend, timestamp = timestamp)) return trends def GetTrendsDaily(self, exclude=None, startdate=None): '''Get the current top trending topics for each hour in a given day Args: startdate: The start date for the report. Should be in the format YYYY-MM-DD. [Optional] exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with 24 entries. Each entry contains the twitter. Trend elements that were trending at the corresponding hour of the day. ''' parameters = {} if exclude: parameters['exclude'] = exclude if not startdate: startdate = time.strftime('%Y-%m-%d', time.gmtime()) parameters['date'] = startdate url = '%s/trends/daily.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] for i in xrange(24): trends.append(None) for t in data['trends']: idx = int(time.strftime('%H', time.strptime(t, '%Y-%m-%d %H:%M'))) trends[idx] = [Trend.NewFromJsonDict(x, timestamp = t) for x in data['trends'][t]] return trends def GetTrendsWeekly(self, exclude=None, startdate=None): '''Get the top 30 trending topics for each day in a given week. Args: startdate: The start date for the report. Should be in the format YYYY-MM-DD. [Optional] exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with each entry contains the twitter. Trend elements of trending topics for the corresponding day of the week ''' parameters = {} if exclude: parameters['exclude'] = exclude if not startdate: startdate = time.strftime('%Y-%m-%d', time.gmtime()) parameters['date'] = startdate url = '%s/trends/weekly.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] for i in xrange(7): trends.append(None) # use the epochs of the dates as keys for a dictionary times = dict([(calendar.timegm(time.strptime(t, '%Y-%m-%d')),t) for t in data['trends']]) cnt = 0 # create the resulting structure ordered by the epochs of the dates for e in sorted(times.keys()): trends[cnt] = [Trend.NewFromJsonDict(x, timestamp = times[e]) for x in data['trends'][times[e]]] cnt +=1 return trends def GetFriendsTimeline(self, user=None, count=None, page=None, since_id=None, retweets=None, include_entities=None): '''Fetch the sequence of twitter.Status messages for a user's friends The twitter.Api instance must be authenticated if the user is private. Args: user: Specifies the ID or screen name of the user for whom to return the friends_timeline. If not specified then the authenticated user set in the twitter.Api instance will be used. [Optional] count: Specifies the number of statuses to retrieve. May not be greater than 100. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] retweets: If True, the timeline will contain native retweets. [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A sequence of twitter.Status instances, one for each message ''' if not user and not self._oauth_consumer: raise TwitterError("User must be specified if API is not authenticated.") url = '%s/statuses/friends_timeline' % self.base_url if user: url = '%s/%s.json' % (url, user) else: url = '%s.json' % url parameters = {} if count is not None: try: if int(count) > 100: raise TwitterError("'count' may not be greater than 100") except ValueError: raise TwitterError("'count' must be an integer") parameters['count'] = count if page is not None: try: parameters['page'] = int(page) except ValueError: raise TwitterError("'page' must be an integer") if since_id: parameters['since_id'] = since_id if retweets: parameters['include_rts'] = True if include_entities: parameters['include_entities'] = 1 json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetUserTimeline(self, id=None, user_id=None, screen_name=None, since_id=None, max_id=None, count=None, page=None, include_rts=None, trim_user=None, include_entities=None, exclude_replies=None): '''Fetch the sequence of public Status messages for a single user. The twitter.Api instance must be authenticated if the user is private. Args: id: Specifies the ID or screen name of the user for whom to return the user_timeline. [Optional] user_id: Specifies the ID of the user for whom to return the user_timeline. Helpful for disambiguating when a valid user ID is also a valid screen name. [Optional] screen_name: Specifies the screen name of the user for whom to return the user_timeline. Helpful for disambiguating when a valid screen name is also a user ID. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns only statuses with an ID less than (that is, older than) or equal to the specified ID. [Optional] count: Specifies the number of statuses to retrieve. May not be greater than 200. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] include_rts: If True, the timeline will contain native retweets (if they exist) in addition to the standard stream of tweets. [Optional] trim_user: If True, statuses will only contain the numerical user ID only. Otherwise a full user object will be returned for each status. [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] exclude_replies: If True, this will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets - this is because the count parameter retrieves that many tweets before filtering out retweets and replies. This parameter is only supported for JSON and XML responses. [Optional] Returns: A sequence of Status instances, one for each message up to count ''' parameters = {} if id: url = '%s/statuses/user_timeline/%s.json' % (self.base_url, id) elif user_id: url = '%s/statuses/user_timeline.json?user_id=%d' % (self.base_url, user_id) elif screen_name: url = ('%s/statuses/user_timeline.json?screen_name=%s' % (self.base_url, screen_name)) elif not self._oauth_consumer: raise TwitterError("User must be specified if API is not authenticated.") else: url = '%s/statuses/user_timeline.json' % self.base_url if since_id: try: parameters['since_id'] = long(since_id) except: raise TwitterError("since_id must be an integer") if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError("max_id must be an integer") if count: try: parameters['count'] = int(count) except: raise TwitterError("count must be an integer") if page: try: parameters['page'] = int(page) except: raise TwitterError("page must be an integer") if include_rts: parameters['include_rts'] = 1 if include_entities: parameters['include_entities'] = 1 if trim_user: parameters['trim_user'] = 1 if exclude_replies: parameters['exclude_replies'] = 1 json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetStatus(self, id, include_entities=None): '''Returns a single status message. The twitter.Api instance must be authenticated if the status message is private. Args: id: The numeric ID of the status you are trying to retrieve. include_entities: If True, each tweet will include a node called "entities". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A twitter.Status instance representing that status message ''' try: if id: long(id) except: raise TwitterError("id must be an long integer") parameters = {} if include_entities: parameters['include_entities'] = 1 url = '%s/statuses/show/%s.json' % (self.base_url, id) json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) def DestroyStatus(self, id): '''Destroys the status specified by the required ID parameter. The twitter.Api instance must be authenticated and the authenticating user must be the author of the specified status. Args: id: The numerical ID of the status you're trying to destroy. Returns: A twitter.Status instance representing the destroyed status message ''' try: if id: long(id) except: raise TwitterError("id must be an integer") url = '%s/statuses/destroy/%s.json' % (self.base_url, id) json = self._FetchUrl(url, post_data={'id': id}) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) @classmethod def _calculate_status_length(cls, status, linksize=19): dummy_link_replacement = 'https://-%d-chars%s/' % (linksize, '-'*(linksize - 18)) shortened = ' '.join([x if not (x.startswith('http://') or x.startswith('https://')) else dummy_link_replacement for x in status.split(' ')]) return len(shortened) def PostUpdate(self, status, in_reply_to_status_id=None, latitude=None, longitude=None): '''Post a twitter status message from the authenticated user. The twitter.Api instance must be authenticated. Args: status: The message text to be posted. Must be less than or equal to 140 characters. in_reply_to_status_id: The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored. [Optional] latitude: Latitude coordinate of the tweet in degrees. Will only work in conjunction with longitude argument. Both longitude and latitude will be ignored by twitter if the user has a false geo_enabled setting. [Optional] longitude: Longitude coordinate of the tweet in degrees. Will only work in conjunction with latitude argument. Both longitude and latitude will be ignored by twitter if the user has a false geo_enabled setting. [Optional] Returns: A twitter.Status instance representing the message posted. ''' if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") url = '%s/statuses/update.json' % self.base_url if isinstance(status, unicode) or self._input_encoding is None: u_status = status else: u_status = unicode(status, self._input_encoding) if self._calculate_status_length(u_status, self._shortlink_size) > CHARACTER_LIMIT: raise TwitterError("Text must be less than or equal to %d characters. " "Consider using PostUpdates." % CHARACTER_LIMIT) data = {'status': status} if in_reply_to_status_id: data['in_reply_to_status_id'] = in_reply_to_status_id if latitude != None and longitude != None: data['lat'] = str(latitude) data['long'] = str(longitude) json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) def PostUpdates(self, status, continuation=None, **kwargs): '''Post one or more twitter status messages from the authenticated user. Unlike api.PostUpdate, this method will post multiple status updates if the message is longer than 140 characters. The twitter.Api instance must be authenticated. Args: status: The message text to be posted. May be longer than 140 characters. continuation: The character string, if any, to be appended to all but the last message. Note that Twitter strips trailing '...' strings from messages. Consider using the unicode \u2026 character (horizontal ellipsis) instead. [Defaults to None] **kwargs: See api.PostUpdate for a list of accepted parameters. Returns: A of list twitter.Status instance representing the messages posted. ''' results = list() if continuation is None: continuation = '' line_length = CHARACTER_LIMIT - len(continuation) lines = textwrap.wrap(status, line_length) for line in lines[0:-1]: results.append(self.PostUpdate(line + continuation, **kwargs)) results.append(self.PostUpdate(lines[-1], **kwargs)) return results def GetUserRetweets(self, count=None, since_id=None, max_id=None, include_entities=False): '''Fetch the sequence of retweets made by a single user. The twitter.Api instance must be authenticated. Args: count: The number of status messages to retrieve. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns results with an ID less than (that is, older than) or equal to the specified ID. [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A sequence of twitter.Status instances, one for each message up to count ''' url = '%s/statuses/retweeted_by_me.json' % self.base_url if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if count is not None: try: if int(count) > 100: raise TwitterError("'count' may not be greater than 100") except ValueError: raise TwitterError("'count' must be an integer") if count: parameters['count'] = count if since_id: parameters['since_id'] = since_id if include_entities: parameters['include_entities'] = True if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError("max_id must be an integer") json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetReplies(self, since=None, since_id=None, page=None): '''Get a sequence of status messages representing the 20 most recent replies (status updates prefixed with @twitterID) to the authenticating user. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] since: Returns: A sequence of twitter.Status instances, one for each reply to the user. ''' url = '%s/statuses/replies.json' % self.base_url if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetRetweets(self, statusid): '''Returns up to 100 of the first retweets of the tweet identified by statusid Args: statusid: The ID of the tweet for which retweets should be searched for Returns: A list of twitter.Status instances, which are retweets of statusid ''' if not self._oauth_consumer: raise TwitterError("The twitter.Api instsance must be authenticated.") url = '%s/statuses/retweets/%s.json?include_entities=true&include_rts=true' % (self.base_url, statusid) parameters = {} json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(s) for s in data] def GetRetweetsOfMe(self, count=None, since_id=None, max_id=None, trim_user=False, include_entities=True, include_user_entities=True): '''Returns up to 100 of the most recent tweets of the user that have been retweeted by others. Args: count: The number of retweets to retrieve, up to 100. If omitted, 20 is assumed. since_id: Returns results with an ID greater than (newer than) this ID. max_id: Returns results with an ID less than or equal to this ID. trim_user: When True, the user object for each tweet will only be an ID. include_entities: When True, the tweet entities will be included. include_user_entities: When True, the user entities will be included. ''' if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") url = '%s/statuses/retweets_of_me.json' % self.base_url parameters = {} if count is not None: try: if int(count) > 100: raise TwitterError("'count' may not be greater than 100") except ValueError: raise TwitterError("'count' must be an integer") if count: parameters['count'] = count if since_id: parameters['since_id'] = since_id if max_id: parameters['max_id'] = max_id if trim_user: parameters['trim_user'] = trim_user if not include_entities: parameters['include_entities'] = include_entities if not include_user_entities: parameters['include_user_entities'] = include_user_entities json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(s) for s in data] def GetFriends(self, user=None, cursor=-1): '''Fetch the sequence of twitter.User instances, one for each friend. The twitter.Api instance must be authenticated. Args: user: The twitter name or id of the user whose friends you are fetching. If not specified, defaults to the authenticated user. [Optional] Returns: A sequence of twitter.User instances, one for each friend ''' if not user and not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") if user: url = '%s/statuses/friends/%s.json' % (self.base_url, user) else: url = '%s/statuses/friends.json' % self.base_url result = [] parameters = {} while True: parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) result += [User.NewFromJsonDict(x) for x in data['users']] if 'next_cursor' in data: if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']: break else: cursor = data['next_cursor'] else: break return result def GetFriendIDs(self, user=None, cursor=-1): '''Returns a list of twitter user id's for every person the specified user is following. Args: user: The id or screen_name of the user to retrieve the id list for [Optional] Returns: A list of integers, one for each user id. ''' if not user and not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") if user: url = '%s/friends/ids/%s.json' % (self.base_url, user) else: url = '%s/friends/ids.json' % self.base_url parameters = {} parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return data def GetFollowerIDs(self, user=None, cursor=-1): '''Returns a list of twitter user id's for every person that is following the specified user. Args: user: The id or screen_name of the user to retrieve the id list for [Optional] Returns: A list of integers, one for each user id. ''' if not user and not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") if user: url = '%s/followers/ids/%s.json' % (self.base_url, user) else: url = '%s/followers/ids.json' % self.base_url parameters = {} parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return data def GetFollowers(self, user=None, cursor=-1): '''Fetch the sequence of twitter.User instances, one for each follower The twitter.Api instance must be authenticated. Args: cursor: Specifies the Twitter API Cursor location to start at. [Optional] Note: there are pagination limits. Returns: A sequence of twitter.User instances, one for each follower ''' if not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") if user: url = '%s/statuses/followers/%s.json' % (self.base_url, user.GetId()) else: url = '%s/statuses/followers.json' % self.base_url result = [] parameters = {} while True: parameters = { 'cursor': cursor } json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) result += [User.NewFromJsonDict(x) for x in data['users']] if 'next_cursor' in data: if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']: break else: cursor = data['next_cursor'] else: break return result def GetFeatured(self): '''Fetch the sequence of twitter.User instances featured on twitter.com The twitter.Api instance must be authenticated. Returns: A sequence of twitter.User instances ''' url = '%s/statuses/featured.json' % self.base_url json = self._FetchUrl(url) data = self._ParseAndCheckTwitter(json) return [User.NewFromJsonDict(x) for x in data] def UsersLookup(self, user_id=None, screen_name=None, users=None): '''Fetch extended information for the specified users. Users may be specified either as lists of either user_ids, screen_names, or twitter.User objects. The list of users that are queried is the union of all specified parameters. The twitter.Api instance must be authenticated. Args: user_id: A list of user_ids to retrieve extended information. [Optional] screen_name: A list of screen_names to retrieve extended information. [Optional] users: A list of twitter.User objects to retrieve extended information. [Optional] Returns: A list of twitter.User objects for the requested users ''' if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") if not user_id and not screen_name and not users: raise TwitterError("Specify at least one of user_id, screen_name, or users.") url = '%s/users/lookup.json' % self.base_url parameters = {} uids = list() if user_id: uids.extend(user_id) if users: uids.extend([u.id for u in users]) if len(uids): parameters['user_id'] = ','.join(["%s" % u for u in uids]) if screen_name: parameters['screen_name'] = ','.join(screen_name) json = self._FetchUrl(url, parameters=parameters) try: data = self._ParseAndCheckTwitter(json) except TwitterError as e: t = e.args[0] if len(t) == 1 and ('code' in t[0]) and (t[0]['code'] == 34): data = [] else: raise return [User.NewFromJsonDict(u) for u in data] def GetUser(self, user): '''Returns a single user. The twitter.Api instance must be authenticated. Args: user: The twitter name or id of the user to retrieve. Returns: A twitter.User instance representing that user ''' url = '%s/users/show/%s.json' % (self.base_url, user) json = self._FetchUrl(url) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def GetDirectMessages(self, since=None, since_id=None, page=None): '''Returns a list of the direct messages sent to the authenticating user. The twitter.Api instance must be authenticated. Args: since: Narrows the returned results to just those statuses created after the specified HTTP-formatted date. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] Returns: A sequence of twitter.DirectMessage instances ''' url = '%s/direct_messages.json' % self.base_url if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [DirectMessage.NewFromJsonDict(x) for x in data] def GetSentDirectMessages(self, since=None, since_id=None, page=None): '''Returns a list of the direct messages sent by the authenticating user. The twitter.Api instance must be authenticated. Args: since: Narrows the returned results to just those statuses created after the specified HTTP-formatted date. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] Returns: A sequence of twitter.DirectMessage instances ''' url = '%s/direct_messages/sent.json' % self.base_url if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [DirectMessage.NewFromJsonDict(x) for x in data] def PostDirectMessage(self, user, text): '''Post a twitter direct message from the authenticated user The twitter.Api instance must be authenticated. Args: user: The ID or screen name of the recipient user. text: The message text to be posted. Must be less than 140 characters. Returns: A twitter.DirectMessage instance representing the message posted ''' if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") url = '%s/direct_messages/new.json' % self.base_url data = {'text': text, 'user': user} json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return DirectMessage.NewFromJsonDict(data) def DestroyDirectMessage(self, id): '''Destroys the direct message specified in the required ID parameter. The twitter.Api instance must be authenticated, and the authenticating user must be the recipient of the specified direct message. Args: id: The id of the direct message to be destroyed Returns: A twitter.DirectMessage instance representing the message destroyed ''' url = '%s/direct_messages/destroy/%s.json' % (self.base_url, id) json = self._FetchUrl(url, post_data={'id': id}) data = self._ParseAndCheckTwitter(json) return DirectMessage.NewFromJsonDict(data) def CreateFriendship(self, user): '''Befriends the user specified in the user parameter as the authenticating user. The twitter.Api instance must be authenticated. Args: The ID or screen name of the user to befriend. Returns: A twitter.User instance representing the befriended user. ''' url = '%s/friendships/create/%s.json' % (self.base_url, user) json = self._FetchUrl(url, post_data={'user': user}) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def DestroyFriendship(self, user): '''Discontinues friendship with the user specified in the user parameter. The twitter.Api instance must be authenticated. Args: The ID or screen name of the user with whom to discontinue friendship. Returns: A twitter.User instance representing the discontinued friend. ''' url = '%s/friendships/destroy/%s.json' % (self.base_url, user) json = self._FetchUrl(url, post_data={'user': user}) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def CreateFavorite(self, status): '''Favorites the status specified in the status parameter as the authenticating user. Returns the favorite status when successful. The twitter.Api instance must be authenticated. Args: The twitter.Status instance to mark as a favorite. Returns: A twitter.Status instance representing the newly-marked favorite. ''' url = '%s/favorites/create/%s.json' % (self.base_url, status.id) json = self._FetchUrl(url, post_data={'id': status.id}) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) def DestroyFavorite(self, status): '''Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful. The twitter.Api instance must be authenticated. Args: The twitter.Status to unmark as a favorite. Returns: A twitter.Status instance representing the newly-unmarked favorite. ''' url = '%s/favorites/destroy/%s.json' % (self.base_url, status.id) json = self._FetchUrl(url, post_data={'id': status.id}) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) def GetFavorites(self, user=None, page=None): '''Return a list of Status objects representing favorited tweets. By default, returns the (up to) 20 most recent tweets for the authenticated user. Args: user: The twitter name or id of the user whose favorites you are fetching. If not specified, defaults to the authenticated user. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] ''' parameters = {} if page: parameters['page'] = page if user: url = '%s/favorites/%s.json' % (self.base_url, user) elif not user and not self._oauth_consumer: raise TwitterError("User must be specified if API is not authenticated.") else: url = '%s/favorites.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetMentions(self, since_id=None, max_id=None, page=None): '''Returns the 20 most recent mentions (status containing @twitterID) for the authenticating user. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns only statuses with an ID less than (that is, older than) the specified ID. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] Returns: A sequence of twitter.Status instances, one for each mention of the user. ''' url = '%s/statuses/mentions.json' % self.base_url if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since_id: parameters['since_id'] = since_id if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError("max_id must be an integer") if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def CreateList(self, user, name, mode=None, description=None): '''Creates a new list with the give name The twitter.Api instance must be authenticated. Args: user: Twitter name to create the list for name: New name for the list mode: 'public' or 'private'. Defaults to 'public'. [Optional] description: Description of the list. [Optional] Returns: A twitter.List instance representing the new list ''' url = '%s/%s/lists.json' % (self.base_url, user) parameters = {'name': name} if mode is not None: parameters['mode'] = mode if description is not None: parameters['description'] = description json = self._FetchUrl(url, post_data=parameters) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data) def DestroyList(self, user, id): '''Destroys the list from the given user The twitter.Api instance must be authenticated. Args: user: The user to remove the list from. id: The slug or id of the list to remove. Returns: A twitter.List instance representing the removed list. ''' url = '%s/%s/lists/%s.json' % (self.base_url, user, id) json = self._FetchUrl(url, post_data={'_method': 'DELETE'}) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data) def CreateSubscription(self, owner, list): '''Creates a subscription to a list by the authenticated user The twitter.Api instance must be authenticated. Args: owner: User name or id of the owner of the list being subscribed to. list: The slug or list id to subscribe the user to Returns: A twitter.List instance representing the list subscribed to ''' url = '%s/%s/%s/subscribers.json' % (self.base_url, owner, list) json = self._FetchUrl(url, post_data={'list_id': list}) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data) def DestroySubscription(self, owner, list): '''Destroys the subscription to a list for the authenticated user The twitter.Api instance must be authenticated. Args: owner: The user id or screen name of the user that owns the list that is to be unsubscribed from list: The slug or list id of the list to unsubscribe from Returns: A twitter.List instance representing the removed list. ''' url = '%s/%s/%s/subscribers.json' % (self.base_url, owner, list) json = self._FetchUrl(url, post_data={'_method': 'DELETE', 'list_id': list}) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data) def GetSubscriptions(self, user, cursor=-1): '''Fetch the sequence of Lists that the given user is subscribed to The twitter.Api instance must be authenticated. Args: user: The twitter name or id of the user cursor: "page" value that Twitter will use to start building the list sequence from. -1 to start at the beginning. Twitter will return in the result the values for next_cursor and previous_cursor. [Optional] Returns: A sequence of twitter.List instances, one for each list ''' if not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") url = '%s/%s/lists/subscriptions.json' % (self.base_url, user) parameters = {} parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [List.NewFromJsonDict(x) for x in data['lists']] def GetLists(self, user, cursor=-1): '''Fetch the sequence of lists for a user. The twitter.Api instance must be authenticated. Args: user: The twitter name or id of the user whose friends you are fetching. If the passed in user is the same as the authenticated user then you will also receive private list data. cursor: "page" value that Twitter will use to start building the list sequence from. -1 to start at the beginning. Twitter will return in the result the values for next_cursor and previous_cursor. [Optional] Returns: A sequence of twitter.List instances, one for each list ''' if not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") url = '%s/%s/lists.json' % (self.base_url, user) parameters = {} parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [List.NewFromJsonDict(x) for x in data['lists']] def GetUserByEmail(self, email): '''Returns a single user by email address. Args: email: The email of the user to retrieve. Returns: A twitter.User instance representing that user ''' url = '%s/users/show.json?email=%s' % (self.base_url, email) json = self._FetchUrl(url) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def VerifyCredentials(self): '''Returns a twitter.User instance if the authenticating user is valid. Returns: A twitter.User instance representing that user if the credentials are valid, None otherwise. ''' if not self._oauth_consumer: raise TwitterError("Api instance must first be given user credentials.") url = '%s/account/verify_credentials.json' % self.base_url try: json = self._FetchUrl(url, no_cache=True) except urllib2.HTTPError, http_error: if http_error.code == httplib.UNAUTHORIZED: return None else: raise http_error data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def SetCache(self, cache): '''Override the default cache. Set to None to prevent caching. Args: cache: An instance that supports the same API as the twitter._FileCache ''' if cache == DEFAULT_CACHE: self._cache = _FileCache() else: self._cache = cache def SetUrllib(self, urllib): '''Override the default urllib implementation. Args: urllib: An instance that supports the same API as the urllib2 module ''' self._urllib = urllib def SetCacheTimeout(self, cache_timeout): '''Override the default cache timeout. Args: cache_timeout: Time, in seconds, that responses should be reused. ''' self._cache_timeout = cache_timeout def SetUserAgent(self, user_agent): '''Override the default user agent Args: user_agent: A string that should be send to the server as the User-agent ''' self._request_headers['User-Agent'] = user_agent def SetXTwitterHeaders(self, client, url, version): '''Set the X-Twitter HTTP headers that will be sent to the server. Args: client: The client name as a string. Will be sent to the server as the 'X-Twitter-Client' header. url: The URL of the meta.xml as a string. Will be sent to the server as the 'X-Twitter-Client-URL' header. version: The client version as a string. Will be sent to the server as the 'X-Twitter-Client-Version' header. ''' self._request_headers['X-Twitter-Client'] = client self._request_headers['X-Twitter-Client-URL'] = url self._request_headers['X-Twitter-Client-Version'] = version def SetSource(self, source): '''Suggest the "from source" value to be displayed on the Twitter web site. The value of the 'source' parameter must be first recognized by the Twitter server. New source values are authorized on a case by case basis by the Twitter development team. Args: source: The source name as a string. Will be sent to the server as the 'source' parameter. ''' self._default_params['source'] = source def GetRateLimitStatus(self): '''Fetch the rate limit status for the currently authorized user. Returns: A dictionary containing the time the limit will reset (reset_time), the number of remaining hits allowed before the reset (remaining_hits), the number of hits allowed in a 60-minute period (hourly_limit), and the time of the reset in seconds since The Epoch (reset_time_in_seconds). ''' url = '%s/account/rate_limit_status.json' % self.base_url json = self._FetchUrl(url, no_cache=True) data = self._ParseAndCheckTwitter(json) return data def MaximumHitFrequency(self): '''Determines the minimum number of seconds that a program must wait before hitting the server again without exceeding the rate_limit imposed for the currently authenticated user. Returns: The minimum second interval that a program must use so as to not exceed the rate_limit imposed for the user. ''' rate_status = self.GetRateLimitStatus() reset_time = rate_status.get('reset_time', None) limit = rate_status.get('remaining_hits', None) if reset_time: # put the reset time into a datetime object reset = datetime.datetime(*rfc822.parsedate(reset_time)[:7]) # find the difference in time between now and the reset time + 1 hour delta = reset + datetime.timedelta(hours=1) - datetime.datetime.utcnow() if not limit: return int(delta.seconds) # determine the minimum number of seconds allowed as a regular interval max_frequency = int(delta.seconds / limit) + 1 # return the number of seconds return max_frequency return 60 def _BuildUrl(self, url, path_elements=None, extra_params=None): # Break url into constituent parts (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url) # Add any additional path elements to the path if path_elements: # Filter out the path elements that have a value of None p = [i for i in path_elements if i] if not path.endswith('/'): path += '/' path += '/'.join(p) # Add any additional query parameters to the query string if extra_params and len(extra_params) > 0: extra_query = self._EncodeParameters(extra_params) # Add it to the existing query if query: query += '&' + extra_query else: query = extra_query # Return the rebuilt URL return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) def _InitializeRequestHeaders(self, request_headers): if request_headers: self._request_headers = request_headers else: self._request_headers = {} def _InitializeUserAgent(self): user_agent = 'Python-urllib/%s (python-twitter/%s)' % \ (self._urllib.__version__, __version__) self.SetUserAgent(user_agent) def _InitializeDefaultParameters(self): self._default_params = {} def _DecompressGzippedResponse(self, response): raw_data = response.read() if response.headers.get('content-encoding', None) == 'gzip': url_data = gzip.GzipFile(fileobj=StringIO.StringIO(raw_data)).read() else: url_data = raw_data return url_data def _Encode(self, s): if self._input_encoding: return unicode(s, self._input_encoding).encode('utf-8') else: return unicode(s).encode('utf-8') def _EncodeParameters(self, parameters): '''Return a string in key=value&key=value form Values of None are not included in the output string. Args: parameters: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form ''' if parameters is None: return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in parameters.items() if v is not None])) def _EncodePostData(self, post_data): '''Return a string in key=value&key=value form Values are assumed to be encoded in the format specified by self._encoding, and are subsequently URL encoded. Args: post_data: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form ''' if post_data is None: return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in post_data.items()])) def _ParseAndCheckTwitter(self, json): """Try and parse the JSON returned from Twitter and return an empty dictionary if there is any error. This is a purely defensive check because during some Twitter network outages it will return an HTML failwhale page.""" try: data = simplejson.loads(json) self._CheckForTwitterError(data) except ValueError: if "<title>Twitter / Over capacity</title>" in json: raise TwitterError("Capacity Error") if "<title>Twitter / Error</title>" in json: raise TwitterError("Technical Error") raise TwitterError("json decoding") return data def _CheckForTwitterError(self, data): """Raises a TwitterError if twitter returns an error message. Args: data: A python dict created from the Twitter json response Raises: TwitterError wrapping the twitter error message if one exists. """ # Twitter errors are relatively unlikely, so it is faster # to check first, rather than try and catch the exception if 'error' in data: raise TwitterError(data['error']) if 'errors' in data: raise TwitterError(data['errors']) def _FetchUrl(self, url, post_data=None, parameters=None, no_cache=None, use_gzip_compression=None): '''Fetch a URL, optionally caching for a specified time. Args: url: The URL to retrieve post_data: A dict of (str, unicode) key/value pairs. If set, POST will be used. parameters: A dict whose key/value pairs should encoded and added to the query string. [Optional] no_cache: If true, overrides the cache on the current request use_gzip_compression: If True, tells the server to gzip-compress the response. It does not apply to POST requests. Defaults to None, which will get the value to use from the instance variable self._use_gzip [Optional] Returns: A string containing the body of the response. ''' # Build the extra parameters dict extra_params = {} if self._default_params: extra_params.update(self._default_params) if parameters: extra_params.update(parameters) if post_data: http_method = "POST" else: http_method = "GET" if self._debugHTTP: _debug = 1 else: _debug = 0 http_handler = self._urllib.HTTPHandler(debuglevel=_debug) https_handler = self._urllib.HTTPSHandler(debuglevel=_debug) http_proxy = os.environ.get('http_proxy') https_proxy = os.environ.get('https_proxy') if http_proxy is None or https_proxy is None : proxy_status = False else : proxy_status = True opener = self._urllib.OpenerDirector() opener.add_handler(http_handler) opener.add_handler(https_handler) if proxy_status is True : proxy_handler = self._urllib.ProxyHandler({'http':str(http_proxy),'https': str(https_proxy)}) opener.add_handler(proxy_handler) if use_gzip_compression is None: use_gzip = self._use_gzip else: use_gzip = use_gzip_compression # Set up compression if use_gzip and not post_data: opener.addheaders.append(('Accept-Encoding', 'gzip')) if self._oauth_consumer is not None: if post_data and http_method == "POST": parameters = post_data.copy() req = oauth.Request.from_consumer_and_token(self._oauth_consumer, token=self._oauth_token, http_method=http_method, http_url=url, parameters=parameters) req.sign_request(self._signature_method_hmac_sha1, self._oauth_consumer, self._oauth_token) headers = req.to_header() if http_method == "POST": encoded_post_data = req.to_postdata() else: encoded_post_data = None url = req.to_url() else: url = self._BuildUrl(url, extra_params=extra_params) encoded_post_data = self._EncodePostData(post_data) # Open and return the URL immediately if we're not going to cache if encoded_post_data or no_cache or not self._cache or not self._cache_timeout: response = opener.open(url, encoded_post_data) url_data = self._DecompressGzippedResponse(response) opener.close() else: # Unique keys are a combination of the url and the oAuth Consumer Key if self._consumer_key: key = self._consumer_key + ':' + url else: key = url # See if it has been cached before last_cached = self._cache.GetCachedTime(key) # If the cached version is outdated then fetch another and store it if not last_cached or time.time() >= last_cached + self._cache_timeout: try: response = opener.open(url, encoded_post_data) url_data = self._DecompressGzippedResponse(response) self._cache.Set(key, url_data) except urllib2.HTTPError, e: print e opener.close() else: url_data = self._cache.Get(key) # Always return the latest version return url_data class _FileCacheError(Exception): '''Base exception class for FileCache related errors''' class _FileCache(object): DEPTH = 3 def __init__(self,root_directory=None): self._InitializeRootDirectory(root_directory) def Get(self,key): path = self._GetPath(key) if os.path.exists(path): return open(path).read() else: return None def Set(self,key,data): path = self._GetPath(key) directory = os.path.dirname(path) if not os.path.exists(directory): os.makedirs(directory) if not os.path.isdir(directory): raise _FileCacheError('%s exists but is not a directory' % directory) temp_fd, temp_path = tempfile.mkstemp() temp_fp = os.fdopen(temp_fd, 'w') temp_fp.write(data) temp_fp.close() if not path.startswith(self._root_directory): raise _FileCacheError('%s does not appear to live under %s' % (path, self._root_directory)) if os.path.exists(path): os.remove(path) os.rename(temp_path, path) def Remove(self,key): path = self._GetPath(key) if not path.startswith(self._root_directory): raise _FileCacheError('%s does not appear to live under %s' % (path, self._root_directory )) if os.path.exists(path): os.remove(path) def GetCachedTime(self,key): path = self._GetPath(key) if os.path.exists(path): return os.path.getmtime(path) else: return None def _GetUsername(self): '''Attempt to find the username in a cross-platform fashion.''' try: return os.getenv('USER') or \ os.getenv('LOGNAME') or \ os.getenv('USERNAME') or \ os.getlogin() or \ 'nobody' except (AttributeError, IOError, OSError), e: return 'nobody' def _GetTmpCachePath(self): username = self._GetUsername() cache_directory = 'python.cache_' + username return os.path.join(tempfile.gettempdir(), cache_directory) def _InitializeRootDirectory(self, root_directory): if not root_directory: root_directory = self._GetTmpCachePath() root_directory = os.path.abspath(root_directory) if not os.path.exists(root_directory): os.mkdir(root_directory) if not os.path.isdir(root_directory): raise _FileCacheError('%s exists but is not a directory' % root_directory) self._root_directory = root_directory def _GetPath(self,key): try: hashed_key = md5(key).hexdigest() except TypeError: hashed_key = md5.new(key).hexdigest() return os.path.join(self._root_directory, self._GetPrefix(hashed_key), hashed_key) def _GetPrefix(self,hashed_key): return os.path.sep.join(hashed_key[0:_FileCache.DEPTH])
123danielbenjaminphilpott-123
twitter.py
Python
asf20
129,982
<html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <meta name="author" content="zouzhongbo" /> <title>117 Countdown</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" charset="utf-8"></script> <script src="https://raw.github.com/dalpo/jquery-countdown/master/js/jquery.countdown.js" charset="utf-8"></script> <script type="text/javascript"> function numToString(num, len) { var str = num.toString(); var n = str.length; for (var i = 0; i < len - n; i++) { str = "0" + str; } return str; } function getStartTime(){ var to = new Date(2016, 7, 8, 8); var from = new Date(); var diff = Math.floor((to - from) / 1000); var days = Math.floor(diff / (3600*24)); diff = diff - (days * 3600 * 24); var hours = Math.floor(diff / 3600); diff = diff - (hours * 3600); var mins = Math.floor(diff / 60); diff = diff - mins * 60; return numToString(days, 4) + ":" + numToString(hours, 2) + ":" + numToString(mins, 2) + ":" + numToString(diff, 2); } $(function(){ var startTime = getStartTime(); $('#counter').countdown({ stepTime: 60, format: 'dddd:hh:mm:ss', startTime: startTime, //digitImages: 6, //--MEDIUM SIZE-- digitWidth: 28, digitHeight: 40, //--SMALLEST SIZE-- //digitWidth: 13, //digitHeight: 18, //--FULL SIZE-- //digitWidth: 53, //digitHeight: 77, image: 'http://117countdown.googlecode.com/hg/digits40.png' }); }); </script> </head> <body> <div id="counter" style="font-size: 30px; zoom: 0.75;"></div> </body> </html>
117countdown
countdown.html
HTML
asf20
2,273
// # MI-r6 // Configuration settings will be stored #define CBundleVersionOfLastInstalled @"BundleVersionOfLastInstalled" #define CDeviceToken @"DeviceToken" #define CUserAgent [NSString stringWithFormat:@"%@/%@/%@/%@/%@",CApplicationName,CVersionNumber,CBuildNumber,DeviceModel,IosFullVersion] #define CProductionMode 0 #if CProductionMode #else #define BASEURL @"http://google.com/api" /// # MI-Facebook #define CFacebookAppId @"395988707164489" /// # MI-Twitter #define CTwitterConsumerKey @"PdLBPYUXlhQpt4AguShUIw" #define CTwitterConsumerSecret @"drdhGuKSingTbsDLtYpob4m5b5dn1abf9XXYyZKQzk" /// # MI-InAppPurchase #define CInAppIdTest @"com.inapp.test" /// # MI-ParsePush #define CParseApplicationId @"Application ID from Parse Push Server for your application" #define CParseClientKey @"Client Key from Parse Push Server for your application" #endif
1234sv
Folder 1/Config1.h
C
mit
888
// # MI-r6 // Configuration settings will be stored // Subfolder 1 #define CBundleVersionOfLastInstalled @"BundleVersionOfLastInstalled" #define CDeviceToken @"DeviceToken" #define CUserAgent [NSString stringWithFormat:@"%@/%@/%@/%@/%@",CApplicationName,CVersionNumber,CBuildNumber,DeviceModel,IosFullVersion] #define CProductionMode 0 #if CProductionMode #else #define BASEURL @"http://google.com/api" /// # MI-Facebook #define CFacebookAppId @"395988707164489" /// # MI-Twitter #define CTwitterConsumerKey @"PdLBPYUXlhQpt4AguShUIw" #define CTwitterConsumerSecret @"drdhGuKSingTbsDLtYpob4m5b5dn1abf9XXYyZKQzk" /// # MI-InAppPurchase #define CInAppIdTest @"com.inapp.test" /// # MI-ParsePush #define CParseApplicationId @"Application ID from Parse Push Server for your application" #define CParseClientKey @"Client Key from Parse Push Server for your application" #endif
1234sv
Folder 1/SubFolder 1/Config Sub1.h
C
mit
903
// # MI-r6 // Configuration settings will be stored // Edit1 // Edit 2 // Edit 34 // Folder 2 #define CBundleVersionOfLastInstalled @"BundleVersionOfLastInstalled" #define CDeviceToken @"DeviceToken" #define CUserAgent [NSString stringWithFormat:@"%@/%@/%@/%@/%@",CApplicationName,CVersionNumber,CBuildNumber,DeviceModel,IosFullVersion] #define CProductionMode 0 #if CProductionMode #else #define BASEURL @"http://google.com/api" /// # MI-Facebook #define CFacebookAppId @"395988707164489" /// # MI-Twitter #define CTwitterConsumerKey @"PdLBPYUXlhQpt4AguShUIw" #define CTwitterConsumerSecret @"drdhGuKSingTbsDLtYpob4m5b5dn1abf9XXYyZKQzk" /// # MI-InAppPurchase #define CInAppIdTest @"com.inapp.test" /// # MI-ParsePush #define CParseApplicationId @"Application ID from Parse Push Server for your application" #define CParseClientKey @"Client Key from Parse Push Server for your application" #endif
1234sv
Folder 2/Config2.h
C
mit
934
using core._1006apparel.security; namespace inside._1006apparel.BusinessLogic { public interface IAuthBusiness { _1006apparelPrincipal Login(string Username, string Password); } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.BusinessLogic/IAuthBusiness.cs
C#
oos
213
using AutoMapper; using core._1006apparel; using core._1006apparel.security; using core._1006apparel.utils; using inside._1006apparel.Entity; using inside._1006apparel.Repository; using log4net; using System.Collections.Generic; using System.Linq; using System.Threading; namespace inside._1006apparel.BusinessLogic { public class AuthBusiness : BusinessBase, IAuthBusiness { private static readonly ILog _log = LogManager.GetLogger(typeof(AuthBusiness)); private readonly IStaffRepository _rpStaff; private readonly IStaffAccountRepository _rpStaffAccount; private readonly IStaffRoleRepository _rpStaffRole; private readonly IMenuRepository _rpMenu; public AuthBusiness( IStaffRepository rpStaff, IStaffAccountRepository rpStaffAccount, IStaffRoleRepository rpStaffRole, IMenuRepository rpMenu) { _rpStaff = rpStaff; _rpStaffAccount = rpStaffAccount; _rpStaffRole = rpStaffRole; _rpMenu = rpMenu; } public _1006apparelPrincipal Login(string Username, string Password) { if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)) { this.AddError("Tài khoản hoặc mật khẩu không hợp lệ"); return null; } var PasswordHashed = HashPassword(Username, Password); var objStaffAccount = _rpStaffAccount.GetBy(Username, PasswordHashed); if (objStaffAccount == null) { this.AddError("Tài khoản hoặc mật khẩu không hợp lệ"); return null; } if (!objStaffAccount.IsActived) { this.AddError("Tài khoản đang tạm ngưng hoạt động"); return null; } var objStaff = _rpStaff.GetBy(objStaffAccount.StaffId); if (objStaff == null) { this.AddError("Tài khoản hoặc mật khẩu không hợp lệ"); return null; } if (this.HasError) { return null; } var session = _1006apparelSession.Current; var principal = session.Principal != null ? session.Principal : new _1006apparelPrincipal(); if (principal._1006apparelIdentity == null) { principal._1006apparelIdentity = new _1006apparelIdentity(); } var listStaffRole = getListRoles(objStaff.Id); principal.Roles = new HashSet<string>(listStaffRole.Select(a => a.RoleId.ToString())); principal.Menus = new SortedSet<MenuModel>(getListMenus(listStaffRole)); principal._1006apparelIdentity.Name = objStaff.Id.ToString(); principal._1006apparelIdentity.StaffId = objStaff.Id; principal._1006apparelIdentity.StaffFullname = objStaff.Fullname; principal._1006apparelIdentity.StaffUsername = objStaffAccount.Username; session.Principal = principal; Thread.CurrentPrincipal = principal; session.UpdateSession(); return principal; } private List<StaffRole> getListRoles(long staffId) { if (staffId <= 0) { return new List<StaffRole>(); } var listStaffRole = _rpStaffRole.GetBy(staffId); if (listStaffRole == null || listStaffRole.Count == 0) { return new List<StaffRole>(); } return listStaffRole; } private List<MenuModel> getListMenus(List<StaffRole> listStaffRole) { if (listStaffRole == null || listStaffRole.Count == 0) { return new List<MenuModel>(); } var listMenu = _rpMenu.GetBy(listStaffRole.Select(a => a.RoleId).ToList()); if (listMenu == null || listMenu.Count == 0) { return new List<MenuModel>(); } var result = Mapper.Map<List<MenuModel>>(listMenu); return result; } private string HashPassword(string Username, string Password) { return ((Username ?? "") + (Password ?? "") + "nvydfz453hzpjbgyvjymsqvsl5khptsm").ToMD5(); } } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.BusinessLogic/AuthBusiness.cs
C#
oos
4,597
using core._1006apparel.security; namespace inside._1006apparel.BusinessLogic { public static class Utils { public static long GetStaffId() { return _1006apparelSession.Current.Principal._1006apparelIdentity.StaffId.Value; } public static string GetStaffFullname() { return _1006apparelSession.Current.Principal._1006apparelIdentity.StaffFullname; } } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.BusinessLogic/Infractstructure/Utils.cs
C#
oos
458
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("inside.1006apparel.BusinessLogic")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("inside.1006apparel.BusinessLogic")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d36d6dcf-e169-4582-b493-e807cdb6370f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
1006apparel
trunk/1006apparel.com/inside.1006apparel.BusinessLogic/Properties/AssemblyInfo.cs
C#
oos
1,476
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("test.1006apparel")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("test.1006apparel")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fa3ac0a0-b151-444c-9ed4-b15ede38886e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
1006apparel
trunk/1006apparel.com/test.1006apparel/Properties/AssemblyInfo.cs
C#
oos
1,444
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using System.Collections.Generic; using core._1006apparel.security; using System.Web; namespace test._1006apparel { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { var aaa = HttpUtility.UrlDecode("<script src=\"/scripts/modules/menu.js\"></script>\n"); var bbb = HttpUtility.HtmlDecode("<script src=\"/scripts/modules/menu.js\"></script>\n"); } } }
1006apparel
trunk/1006apparel.com/test.1006apparel/UnitTest1.cs
C#
oos
578
using System; using Microsoft.Practices.Unity; namespace core._1006apparel.App_Start { /// <summary> /// Specifies the Unity configuration for the main container. /// </summary> public class UnityConfig { #region Unity Container private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() => { var container = new UnityContainer(); RegisterTypes(container); return container; }); /// <summary> /// Gets the configured Unity container. /// </summary> public static IUnityContainer GetConfiguredContainer() { return container.Value; } #endregion /// <summary>Registers the type mappings with the Unity container.</summary> /// <param name="container">The unity container to configure.</param> /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks> public static void RegisterTypes(IUnityContainer container) { // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements. // container.LoadConfiguration(); // TODO: Register your types here // container.RegisterType<IProductRepository, ProductRepository>(); } } }
1006apparel
trunk/1006apparel.com/core.1006apparel/App_Start/UnityConfig.cs
C#
oos
1,602
using Microsoft.Practices.ServiceLocation; namespace core._1006apparel { public class IoC { public static T Get<T>() { return ServiceLocator.Current.GetInstance<T>(); } } }
1006apparel
trunk/1006apparel.com/core.1006apparel/IoC.cs
C#
oos
237
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Practices.ServiceLocation; using System.Data.Entity.Core; namespace core._1006apparel { public class BusinessProcess : IDisposable { private object _resultObj = null; private Dictionary<string, List<object>> _errors = null; private Dictionary<string, List<object>> _infos = null; private bool _hasError = false; private bool _hasInfo = false; public BusinessProcess Process(Action<BusinessProcess> action) { //Check Error if (this.HasError) return this; try { action(this); } catch (OptimisticConcurrencyException ex) { __handleException(ex); } catch (System.Security.SecurityException ex) { __handleException(ex); } return this; } public BusinessProcess Process(Func<BusinessProcess, object> func) { //Check Error if (this.HasError) return this; try { _resultObj = func(this); } catch (OptimisticConcurrencyException ex) { __handleException(ex); } catch (System.Security.SecurityException ex) { __handleException(ex); } return this; } private void __handleException(Exception ex) { if (ex is OptimisticConcurrencyException) { this.AddError(this.GetType(), "Dữ liệu đã bị thay đổi. Vui lòng cập nhật lại dữ liệu mới."); } if (ex is System.Security.SecurityException) { this.AddError(this.GetType(), "Bạn không có quyền thực hiện thao tác này."); } } public static BusinessProcess Current { get { return ServiceLocator.Current.GetInstance<BusinessProcess>(); } } public T GetLastResult<T>() where T : class { return _resultObj as T; } public object GetLastResult() { return _resultObj; } public bool HasError { get { return _hasError; } private set { _hasError = value; } } public bool HasInfo { get { return _hasInfo; } private set { _hasInfo = value; } } #region Errors public void AddError<Business>(object errorObj) { this.AddError(typeof(Business), errorObj); } public void AddError(object errorObj) { AddError(null, errorObj); } public void AddError(Type businessType, object errorObj) { if (!HasError) { HasError = true; _errors = new Dictionary<string, List<object>>(); } string typeName = businessType == null ? "Null" : businessType.Name; List<object> listObj; if (!_errors.ContainsKey(typeName)) { listObj = new List<object>(); _errors.Add(typeName, listObj); } else listObj = _errors[typeName]; listObj.Add(errorObj); } public List<Result> GetErrors<Business, Result>() { if (HasError) { string typeName = typeof(Business).Name; if (_errors.ContainsKey(typeName)) { return _errors[typeName].OfType<Result>().ToList(); } } return null; } public List<object> GetErrors<Business>() { if (HasError) { string typeName = typeof(Business).Name; if (_errors.ContainsKey(typeName)) { return _errors[typeName]; } } return null; } public List<object> GetErrors() { if (HasError) { return _errors.Values.Aggregate((r, a) => { r.AddRange(a); return r; }); } return null; } #endregion #region Infos public void AddInfo<Business>(object infoObj) { AddInfo(typeof(Business), infoObj); } public void AddInfo(object infoObj) { AddError(null, infoObj); } public void AddInfo(Type businessType, object infoObj) { if (!HasInfo) { HasInfo = true; _infos = new Dictionary<string, List<object>>(); } string typeName = businessType == null ? "Null" : businessType.Name; List<object> listObj; if (!_infos.ContainsKey(typeName)) { listObj = new List<object>(); _infos.Add(typeName, listObj); } else listObj = _infos[typeName]; listObj.Add(infoObj); } public List<object> GetInfos(Type businessType, Type resultType) { if (HasInfo) { string typeName = businessType.Name; if (_infos.ContainsKey(typeName)) { return _infos[typeName].Where(m => m.GetType() == resultType).ToList(); } } return null; } public List<Result> GetInfos<Business, Result>() { return GetInfos(typeof(Business), typeof(Result)).Cast<Result>().ToList(); } public List<object> GetInfos(Type businessType) { if (HasInfo) { string typeName = businessType.Name; if (_infos.ContainsKey(typeName)) { return _infos[typeName]; } } return null; } public List<object> GetInfos<Business>() { return GetInfos(typeof(Business)); } public List<object> GetInfos() { if (HasInfo) { return _infos.Values.Aggregate((r, a) => { r.AddRange(a); return r; }); } return null; } #endregion private bool disposing = false; public void Dispose() { if (!disposing) { disposing = true; if (_resultObj is IDisposable) { ((IDisposable)_resultObj).Dispose(); } if (_errors != null) _errors.Clear(); if (_infos != null) _infos.Clear(); _hasError = false; _hasInfo = false; } } } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Business/BusinessProcess.cs
C#
oos
7,718
using System.Collections.Generic; namespace core._1006apparel { public class BusinessBase : IBusiness { private BusinessProcess businessProcess = BusinessProcess.Current; protected void AddError(object obj) { businessProcess.AddError(this.GetType(), obj); } protected void AddInfo(object obj) { businessProcess.AddInfo(this.GetType(), obj); } protected List<object> GetInfos() { return businessProcess.GetInfos(); } protected bool HasError { get { return businessProcess.HasError; } } } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Business/BusinessBase.cs
C#
oos
733
namespace core._1006apparel { public interface IBusiness { } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Business/IBusiness.cs
C#
oos
84
using System.Runtime.Serialization; namespace core._1006apparel.Entity { [DataContract] public enum ObjectState { [EnumMember] Unchanged, [EnumMember] Added, [EnumMember] Modified, [EnumMember] Deleted } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Entity/ObjectState.cs
C#
oos
307
namespace core._1006apparel.Entity { public interface IEntity { } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Entity/IEntity.cs
C#
oos
89
using System; using System.Runtime.Serialization; namespace core._1006apparel.Entity { [DataContract(IsReference = true)] public class EntityBase : IEntity { [NonSerialized] public bool UpdateMethodCalled = false; [DataMember] public ObjectState ObjectState { get; set; } } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Entity/EntityBase.cs
C#
oos
344
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("core.1006apparel")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("core.1006apparel")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5aa32b79-ff99-4e45-abad-e9c4b2595fe2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
1006apparel
trunk/1006apparel.com/core.1006apparel/Properties/AssemblyInfo.cs
C#
oos
1,444
using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Linq.Expressions; using core._1006apparel.Entity; using core._1006apparel.utils; using System.Data.Entity.Core.Objects; using System.Data.Entity.Core; using System.Data.Entity; namespace core._1006apparel.Repository { public abstract class EFRepository<TEntity> : IRepository<TEntity> where TEntity : class { #region Vars const string VERSIONNO = "VERSIONNO"; private readonly ObjectContext _objContext; private readonly EFUnitOfWork _unitOfWork; private ObjectSet<TEntity> _objSet; private ObjectSet<TEntity> ObjSet { get { if (_objSet == null) { _objSet = _objContext.CreateObjectSet<TEntity>(); } return _objSet; } } #endregion #region Constructors public EFRepository(IUnitOfWork unitOfWork) { _objContext = unitOfWork.Context; _unitOfWork = unitOfWork as EFUnitOfWork; } #endregion #region Protected Methods /// <summary> /// Gets the repository query. /// </summary> /// <value>The repository query.</value> protected virtual IQueryable<TEntity> RepositoryQuery { get { return this.ObjSet.AsQueryable<TEntity>(); } } /// <summary> /// Gets the repository query. /// </summary> /// <value>The repository query.</value> protected virtual IQueryable<TEntity> Include(params Expression<Func<TEntity, object>>[] navigateProperties) { ObjectQuery<TEntity> objquery = null; foreach (var property in navigateProperties) { string propertyName = property.GetPropertyName(); if (objquery == null) objquery = this.ObjSet.Include(propertyName); else objquery = objquery.Include(propertyName); } return objquery; } /// <summary> /// Exec Store /// </summary> /// <param name="storeName"></param> /// <param name="paras"></param> protected void ExecStore(string storeName, params ObjectParameter[] paras) { this._objContext.ExecuteFunction(storeName, paras); } #endregion #region IRepository<TEntity> Members public virtual TEntity Create() { return this.ObjSet.CreateObject(); } public virtual IEnumerable<TEntity> GetAll() { return this.RepositoryQuery.ToList(); } public virtual void Add(TEntity entity) { this.ObjSet.AddObject(entity); } public virtual void Update(TEntity entity, params Expression<Func<TEntity, object>>[] properties) { var entityKey = GetEntityKey(entity); //Flag Update Called var entityBase = entity as EntityBase; if (entityBase != null) { entityBase.UpdateMethodCalled = true; } //Attach Obj If Entity is Detached ObjectStateEntry updateObjState; _objContext.ObjectStateManager.TryGetObjectStateEntry(entityKey, out updateObjState); bool isAttached = false; bool isUpdateMap = false; if (updateObjState == null || updateObjState.State == EntityState.Detached) { this.ObjSet.Attach(entity); //Update State _objContext.ObjectStateManager.TryGetObjectStateEntry(entity, out updateObjState); isAttached = true; } else { if (updateObjState.Entity != entity) { //Check Version __checkVersion(updateObjState.Entity, entity); if ((updateObjState.Entity as EntityBase) != null) (updateObjState.Entity as EntityBase).UpdateMethodCalled = true; isUpdateMap = true; } } // if (properties == null || !properties.Any()) { //Update All Property if (isAttached) { _objContext.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified); } else { if (isUpdateMap) { __copyEntityProperties(entity, updateObjState.Entity); } } } else { if (!isAttached) { //Reset Changed updateObjState.ChangeState(EntityState.Unchanged); _objContext.ObjectStateManager.TryGetObjectStateEntry(entityKey, out updateObjState); if (isUpdateMap) { __copyEntityProperties(entity, updateObjState.Entity, properties); } } //Set Property foreach (var property in properties) { string propertyName = property.GetPropertyName(); updateObjState.SetModifiedProperty(propertyName); } } } public virtual void Delete(TEntity entity) { TEntity _entity = entity; ObjectStateEntry deletedObj; _objContext.ObjectStateManager.TryGetObjectStateEntry(GetEntityKey(_entity), out deletedObj); if (deletedObj == null || deletedObj.State == EntityState.Detached) { this.ObjSet.Attach(_entity); } else { object obj; if (_objContext.TryGetObjectByKey(GetEntityKey(_entity), out obj)) _entity = obj as TEntity; else throw new ArgumentException("entity"); } //Because After Delete, Navigate Property Reset To Null, Can't Update Version Of Related Object (Bug) _unitOfWork.BeforeDeleteEntity(_entity); this.ObjSet.DeleteObject(_entity); } protected virtual IEnumerable<TEntity> Find(ISpecification<TEntity> specification) { return this.RepositoryQuery.Where(specification.Predicate).ToList(); } #endregion #region Private Method public EntityKey GetEntityKey(TEntity entity) { return _objContext.CreateEntityKey(ObjSet.EntitySet.Name, entity); } private void __checkVersion(object entity, object toEntity) { var property = entity.GetType().GetProperty(VERSIONNO); if (property == null) return; if (!property.GetValue(entity, null).Equals(property.GetValue(toEntity, null))) throw new OptimisticConcurrencyException("Version"); } private void __copyEntityProperties(object entity, object toEntity, params Expression<Func<TEntity, object>>[] properties) { string[] stringProperties = properties.Select(m => m.GetPropertyName()).ToArray(); __copyEntityProperties(entity, toEntity, stringProperties); } private void __copyEntityProperties(object entity, object toEntity, string[] properties) { Type type = entity.GetType(); foreach (string property in properties) { var entityProperty = type.GetProperty(property); var value = entityProperty.GetValue(entity, null); entityProperty.SetValue(toEntity, value, null); } } private void __copyEntityProperties(object entity, object toEntity) { string[] properties = this.ObjSet.EntitySet.ElementType.Properties.Select(m => m.Name).ToArray(); __copyEntityProperties(entity, toEntity, properties); } #endregion } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Repository/EFRepository.cs
C#
oos
8,567
using System; using System.Linq.Expressions; namespace core._1006apparel.Repository { public interface ISpecification<TEntity> { // <summary> /// The criteria of the Specification. /// </summary> Expression<Func<TEntity, bool>> Predicate { get; } /// <summary> /// Return true/false whethe the Entity object meet the criteria encapsulated by the /// Specification. /// </summary> /// <param name="entity"></param> /// <returns></returns> bool IsSatisfiedBy(TEntity entity); } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Repository/ISpecification.cs
C#
oos
604
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Data; using core._1006apparel.Entity; using System.Data.Entity; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Core.Objects; using System.Data.Entity.Core; using System.Data.Entity.Infrastructure; namespace core._1006apparel.Repository { public class EFUnitOfWork : IUnitOfWork, IDisposable { #region Vars const string VERSIONNO = "VERSIONNO"; const string CREATEDUSER = "CREATEDUSER"; const string CREATEDDATE = "CREATEDDATE"; const string UPDATEDUSER = "UPDATEDUSER"; const string UPDATEDDATE = "UPDATEDDATE"; readonly ObjectContext _context; #endregion #region Constructors public EFUnitOfWork(IObjectContext context) { _context = ((IObjectContextAdapter)context).ObjectContext; } #endregion #region IUnitOfWork Members public ObjectContext Context { get { return _context; } } public void Commit() { //POCO Detect Changes _context.DetectChanges(); _context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified).ToList().ForEach(entityState => { Type entityType = entityState.Entity.GetType(); var optimisticLockFieldProperty = entityType.GetProperty(VERSIONNO); var updatedUserFieldProperty = entityType.GetProperty(UPDATEDUSER); var updatedDateFieldProperty = entityType.GetProperty(UPDATEDDATE); string userName = Thread.CurrentPrincipal.Identity.IsAuthenticated ? Thread.CurrentPrincipal.Identity.Name : "NULL"; #region Add if (entityState.State == EntityState.Added) { //Set 1 for New Object Decimal? newOptimisticValue = 1; if (optimisticLockFieldProperty != null) optimisticLockFieldProperty.SetValue(entityState.Entity, newOptimisticValue, null); var createdUserFieldProperty = entityType.GetProperty(CREATEDUSER); var createdDateFieldProperty = entityType.GetProperty(CREATEDDATE); if (createdUserFieldProperty != null) createdUserFieldProperty.SetValue(entityState.Entity, userName, null); if (createdDateFieldProperty != null) createdDateFieldProperty.SetValue(entityState.Entity, DateTime.Now, null); } #endregion #region Modified if (entityState.State == EntityState.Modified) { //Check Update Method Called var entityBase = entityState.Entity as EntityBase; if (entityBase != null) { if (!entityBase.UpdateMethodCalled) throw new Exception("Please Call Repository Update To Update Entity"); entityBase.UpdateMethodCalled = false; } //Set +1 for Modified Object if (optimisticLockFieldProperty != null) { Decimal? newOptimisticValue = 1; object currValue = optimisticLockFieldProperty.GetValue(entityState.Entity, null); if (currValue != null) { newOptimisticValue = Decimal.Parse(currValue.ToString()) + 1; } optimisticLockFieldProperty.SetValue(entityState.Entity, newOptimisticValue, null); entityState.SetModifiedProperty(optimisticLockFieldProperty.Name); } //Set Modify When POCO Object Is Detached if (updatedUserFieldProperty != null) entityState.SetModifiedProperty(updatedUserFieldProperty.Name); if (updatedDateFieldProperty != null) entityState.SetModifiedProperty(updatedDateFieldProperty.Name); } #endregion if (updatedUserFieldProperty != null) updatedUserFieldProperty.SetValue(entityState.Entity, userName, null); if (updatedDateFieldProperty != null) updatedDateFieldProperty.SetValue(entityState.Entity, DateTime.Now, null); }); //Fix Bug http://support.microsoft.com/kb/2390624 //Using When Not Install Hot Fix __updateVersionRelationObject(); // _context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave); } //TEMP: Temporary : Update Repo, UnitOfWork Fix Bug Delete (Relation Reset To Null, Can't Update Relation) //TODO: Review #region HotFix2390624 List<object> _listNavigateOBjectsOfDeleted = new List<object>(); /// <summary> /// Get Child Entities Of Navigate Property /// </summary> /// <param name="listNavigateObject"></param> /// <param name="entity"></param> private void __getChildEntities(List<object> listNavigateObject, object entity) { var entitySet = _context.MetadataWorkspace.GetEntityContainer(_context.DefaultContainerName, DataSpace.CSpace) .BaseEntitySets.Where(m => m.ElementType.Name == entity.GetType().Name).First(); entitySet.ElementType.Members.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.NavigationProperty) .ToList().ForEach(navigateProperty => { var navigateValue = entity.GetType() .GetProperty(navigateProperty.Name).GetValue(entity, null); if (navigateValue is EntityBase) { if (_context.ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged).Any(m => m.Entity == navigateValue)) { if (!listNavigateObject.Contains(navigateValue)) { listNavigateObject.Add(navigateValue); __getChildEntities(listNavigateObject, navigateValue); } } } }); } private string __getPropertyNameFromNavigateProperty(NavigationProperty navProperty) { AssociationType assType = navProperty.RelationshipType as AssociationType; if (assType == null) return null; ReferentialConstraint refConstrain = assType.ReferentialConstraints.FirstOrDefault(); if (refConstrain == null) return null; var toProperty = refConstrain.FromProperties.FirstOrDefault(); return toProperty.Name; } private object __tryGetObjectFromOriginalNavigateProperty(EntitySetBase entitySet, object originalValue, NavigationProperty navProperty) { var assType = navProperty.RelationshipType as AssociationType; if (assType == null) return null; var refConstrain = assType.ReferentialConstraints.FirstOrDefault(); if (refConstrain == null) return null; var fromProperty = refConstrain.ToProperties.FirstOrDefault(); var toProperty = refConstrain.FromProperties.FirstOrDefault(); if (fromProperty == null || toProperty == null) return null; var propertyValue = originalValue; if (propertyValue == null || propertyValue == DBNull.Value) return null; var keyMember = new EntityKeyMember(toProperty.Name, propertyValue); var key = new EntityKey(entitySet.EntityContainer + "." + navProperty.ToEndMember.Name, new EntityKeyMember[] { keyMember }); var findObj = _context.ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged) .Where(m => m.EntityKey == key).Select(k => k.Entity).FirstOrDefault(); return findObj; } private object __tryGetObjectFromNavigateProperty(EntitySetBase entitySet, object entity, NavigationProperty navProperty) { AssociationType assType = navProperty.RelationshipType as AssociationType; if (assType == null) return null; ReferentialConstraint refConstrain = assType.ReferentialConstraints.FirstOrDefault(); if (refConstrain == null) return null; var fromProperty = refConstrain.ToProperties.FirstOrDefault(); var toProperty = refConstrain.FromProperties.FirstOrDefault(); if (fromProperty == null || toProperty == null) return null; var propertyValue = entity.GetType().GetProperty(fromProperty.Name).GetValue(entity, null); if (propertyValue == null) return null; var keyMember = new EntityKeyMember(toProperty.Name, propertyValue); var key = new EntityKey(entitySet.EntityContainer + "." + navProperty.ToEndMember.Name, new EntityKeyMember[] { keyMember }); var findObj = _context.ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged) .Where(m => m.EntityKey == key).Select(k => k.Entity).FirstOrDefault(); return findObj; } private void __updateVersionRelationObject() { List<ObjectStateEntry> entityStates = _context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified).ToList(); List<object> listNavigateOBjects = new List<object>(); //Get Entity And Set Name var entitySets = from set in _context.MetadataWorkspace.GetEntityContainer(_context.DefaultContainerName, DataSpace.CSpace).BaseEntitySets join entityState in entityStates on set.ElementType.Name equals entityState.Entity.GetType().Name select new { set, entityState }; entitySets.ToList().ForEach(entitySet => { entitySet.set.ElementType.Members.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.NavigationProperty) .ToList().ForEach(navigateProperty => { var navigateValue = entitySet.entityState.Entity.GetType() .GetProperty(navigateProperty.Name).GetValue(entitySet.entityState.Entity, null); if (navigateValue == null) navigateValue = __tryGetObjectFromNavigateProperty(entitySet.set, entitySet.entityState.Entity, navigateProperty as NavigationProperty); if (navigateValue is EntityBase) { if (_context.ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged).Any(m => m.Entity == navigateValue)) { listNavigateOBjects.Add(navigateValue); __getChildEntities(listNavigateOBjects, navigateValue); } } //If Navigate Is Update, => Update Version For Original Value var propertyName = __getPropertyNameFromNavigateProperty(navigateProperty as NavigationProperty); if (entitySet.entityState.GetModifiedProperties().Contains(propertyName)) { var navigateOldValue = __tryGetObjectFromOriginalNavigateProperty(entitySet.set, entitySet.entityState.OriginalValues[propertyName], navigateProperty as NavigationProperty); if (navigateOldValue is EntityBase) { if (_context.ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged).Any(m => m.Entity == navigateValue)) { listNavigateOBjects.Add(navigateOldValue); __getChildEntities(listNavigateOBjects, navigateOldValue); } } } }); }); listNavigateOBjects.AddRange(_listNavigateOBjectsOfDeleted); //Reset _listNavigateOBjectsOfDeleted.Clear(); foreach (object entity in listNavigateOBjects) { //Change To Modify To Increase Version if (entity.GetType().GetProperty(VERSIONNO) != null) _context.ObjectStateManager.GetObjectStateEntry(entity).SetModifiedProperty(VERSIONNO); } } internal void BeforeDeleteEntity(object entity) { //Get Entity And Set Name var entitySet = (from set in _context.MetadataWorkspace.GetEntityContainer(_context.DefaultContainerName, DataSpace.CSpace).BaseEntitySets where set.ElementType.Name == entity.GetType().Name select new { set, entity }).First(); entitySet.set.ElementType.Members.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.NavigationProperty) .ToList().ForEach(navigateProperty => { var navigateValue = entitySet.entity.GetType() .GetProperty(navigateProperty.Name).GetValue(entitySet.entity, null); if (navigateValue == null) navigateValue = __tryGetObjectFromNavigateProperty(entitySet.set, entitySet.entity, navigateProperty as NavigationProperty); if (navigateValue is EntityBase) { if (_context.ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged).Any(m => m.Entity == navigateValue)) { _listNavigateOBjectsOfDeleted.Add(navigateValue); __getChildEntities(_listNavigateOBjectsOfDeleted, navigateValue); } } }); } #endregion #endregion #region IDisposable Members private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { _context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Repository/EFUnitOfWork.cs
C#
oos
15,447
using System; using System.Collections.Generic; using System.Linq.Expressions; namespace core._1006apparel.Repository { public interface IRepository<TEntity> where TEntity : class { /// <summary> /// Create a new Entity Object /// </summary> /// <returns>Entity object of type <typeparamref name="TEntity"/></returns> TEntity Create(); /// <summary> /// Gets all. /// </summary> /// <returns></returns> IEnumerable<TEntity> GetAll(); /// <summary> /// Add the Entity Object to the Repository /// </summary> /// <param name="entity">The Entity object to add</param> void Add(TEntity entity); /// <summary> /// Update changes made to the Entity object in the repository /// </summary> /// <param name="entity">The Entity object to update</param> void Update(TEntity entity, params Expression<Func<TEntity, object>>[] properties); /// <summary> /// Delete the Entity object from the repository /// </summary> /// <param name="entity">The Entity object to delete</param> void Delete(TEntity entity); ///// <summary> ///// Find the Entity object(s) based on specification. ///// </summary> ///// <param name="specification"></param> //IEnumerable<TEntity> Find(ISpecification<TEntity> specification); } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Repository/IRepository.cs
C#
oos
1,505
using System; using System.Data.Entity.Core.Objects; namespace core._1006apparel.Repository { public interface IUnitOfWork : IDisposable { ObjectContext Context { get; } void Commit(); } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Repository/IUnitOfWork.cs
C#
oos
232
namespace core._1006apparel.Repository { public interface IObjectContext { } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Repository/IObjectContext.cs
C#
oos
100
namespace core._1006apparel.Service { public static class ResponseHelper { public static Response ToResponse(this BusinessProcess process) { Response rp = new Response(); rp.Infos = process.GetInfos(); rp.Errors = process.GetErrors(); BusinessProcess.Current.Dispose(); return rp; } public static Response<T> ToResponse<T>(this BusinessProcess process, T data) { Response<T> rp = new Response<T>(data); rp.Infos = process.GetInfos(); rp.Errors = process.GetErrors(); BusinessProcess.Current.Dispose(); return rp; } } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Service/ResponseHelper.cs
C#
oos
726
using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; namespace core._1006apparel.Service { [DataContract(IsReference = true)] public class Response { public Response() { Infos = new List<object>(); Errors = new List<object>(); } [IgnoreDataMember] public bool HasError { get { if (Errors != null && Errors.Any()) { return true; } else { return false; } } } [IgnoreDataMember] public bool HasInfo { get { if (Infos != null && Infos.Any()) { return true; } else { return false; } } } [DataMember] public List<object> Infos { get; set; } [DataMember] public List<object> Errors { get; set; } public string ToErrorMsg() { if (HasError) { return Errors.Aggregate((a, b) => { return (a ?? "").ToString() + "\n" + (b ?? "").ToString(); }).ToString(); } return null; } public string FirstErrorMsg() { if (HasError) { return Errors[0].ToString(); } return null; } public string ToInfoMsg() { if (HasInfo) { return Infos.Aggregate((a, b) => { return a.ToString() + "\n" + b.ToString(); }).ToString(); } return null; } public string FirstInfoMsg() { if (HasInfo) { return Infos[0].ToString(); } return null; } public static Response<T> FromData<T>(T data) { Response<T> rp = new Response<T>(data); return rp; } } [DataContract] public class Response<T> : Response { public Response() { } public Response(T data) { Data = data; } [DataMember] public T Data { get; set; } } }
1006apparel
trunk/1006apparel.com/core.1006apparel/Service/Response.cs
C#
oos
2,623
using core._1006apparel; using core._1006apparel.security; using core._1006apparel.Service; using inside._1006apparel.BusinessLogic; using System.ServiceModel; namespace inside._1006apparel.Services { [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerCall)] public partial class inside1006apparelServices : inside1006apparelIServices { public Response<_1006apparelPrincipal> Login(string Username, string Password) { var result = IoC.Get<IAuthBusiness>().Login(Username, Password); return BusinessProcess.Current.ToResponse(BusinessProcess.Current.HasError ? null : result); } } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Services/inside.1006apparel.service.cs
C#
oos
725
using core._1006apparel.SharedObject; using Newtonsoft.Json; using System.Web; [assembly: PreApplicationStartMethod(typeof(inside._1006apparel.Services.App_Start.Startup), "Start")] namespace inside._1006apparel.Services.App_Start { public class Startup { public static void Start() { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { MaxDepth = GlobalDefaultData.JsonSerializerSettings.MaxDepth }; MapperConfig.Init(); } } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Services/App_Start/Startup.cs
C#
oos
566
using core._1006apparel; using core._1006apparel.Repository; using inside._1006apparel.BusinessLogic; using inside._1006apparel.Entity; using inside._1006apparel.Repository; using Microsoft.Practices.Unity; namespace inside._1006apparel.Services { public class UnityConfig { public static IUnityContainer Init(IUnityContainer ctn) { return Register(ctn); } private static IUnityContainer Register(IUnityContainer ctn) { #region System ctn.RegisterType<IUnitOfWork, EFUnitOfWork>(new PerRequestLifetimeManager()); ctn.RegisterType<IObjectContext, inside1006apparelEntities>(new PerRequestLifetimeManager(), new InjectionFactory(ct => { #if DEBUG return new inside1006apparelEntities("metadata=res://*/inside.csdl|res://*/inside.ssdl|res://*/inside.msl;provider=System.Data.SqlClient;provider connection string='data source=hazel.arvixe.com;initial catalog=inside.1006apparel.com;persist security info=True;user id=inside.1006apparel.com;password=bLxr5aP7Ku8u;multipleactiveresultsets=True;application name=EntityFramework'"); #else return new inside1006apparelEntities("metadata=res://*/inside.csdl|res://*/inside.ssdl|res://*/inside.msl;provider=System.Data.SqlClient;provider connection string='data source=127.0.0.1;initial catalog=inside.1006apparel.com;persist security info=True;user id=inside.1006apparel.com;password=bLxr5aP7Ku8u;multipleactiveresultsets=True;application name=EntityFramework'"); #endif })); ctn.RegisterType<BusinessProcess>(new PerRequestLifetimeManager()); #endregion #region Business ctn.RegisterType<IAuthBusiness, AuthBusiness>(new PerRequestLifetimeManager()); #endregion #region Repository ctn.RegisterType<IMenuRepository, MenuRepository>(new PerRequestLifetimeManager()); ctn.RegisterType<IRoleRepository, RoleRepository>(new PerRequestLifetimeManager()); ctn.RegisterType<IStaffRepository, StaffRepository>(new PerRequestLifetimeManager()); ctn.RegisterType<IStaffAccountRepository, StaffAccountRepository>(new PerRequestLifetimeManager()); ctn.RegisterType<IStaffRoleRepository, StaffRoleRepository>(new PerRequestLifetimeManager()); #endregion return ctn; } } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Services/App_Start/UnityConfig.cs
C#
oos
2,488
using AutoMapper; using core._1006apparel.security; using inside._1006apparel.Entity; namespace inside._1006apparel.Services.App_Start { public class MapperConfig { public static void Init() { Mapper.CreateMap<Menu, MenuModel>(); } } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Services/App_Start/MapperConfig.cs
C#
oos
302
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("inside.1006apparel.Services")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("inside.1006apparel.Services")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8d634540-1213-4986-b0b0-dfbeb4af1fdc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
1006apparel
trunk/1006apparel.com/inside.1006apparel.Services/Properties/AssemblyInfo.cs
C#
oos
1,466
using core._1006apparel.security; using core._1006apparel.Service; namespace inside._1006apparel.Services { public interface inside1006apparelIServices { Response<_1006apparelPrincipal> Login(string Username, string Password); } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Services/inside.1006apparel.Iservice.cs
C#
oos
265
namespace core._1006apparel.SharedObject { public class GlobalDefaultData { public class JsonSerializerSettings { public const int MaxDepth = 10; } } }
1006apparel
trunk/1006apparel.com/core.1006apparel.SharedObject/GlobalDefaultData.cs
C#
oos
213
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("core.1006apparel.SharedObject")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("core.1006apparel.SharedObject")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c01822f5-8c77-4d75-ae2b-fa336af3196b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
1006apparel
trunk/1006apparel.com/core.1006apparel.SharedObject/Properties/AssemblyInfo.cs
C#
oos
1,470
using core._1006apparel.Repository; using inside._1006apparel.Entity; namespace inside._1006apparel.Repository { public class RoleRepository : EFRepository<Role>, IRoleRepository { public RoleRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Repository/RoleRepository.cs
C#
oos
288
using core._1006apparel.Repository; using inside._1006apparel.Entity; using System.Collections.Generic; namespace inside._1006apparel.Repository { public interface IMenuRepository : IRepository<Menu> { List<Menu> GetBy(List<long> listRoleId); } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Repository/IMenuRepository.cs
C#
oos
282
using core._1006apparel.Repository; using inside._1006apparel.Entity; using System.Collections.Generic; using System.Linq; namespace inside._1006apparel.Repository { public class MenuRepository : EFRepository<Menu>, IMenuRepository { public MenuRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } public List<Menu> GetBy(List<long> listRoleId) { return RepositoryQuery.Where(a => a.MenuRole.Any(b => listRoleId.Contains(b.RoleId))).ToList(); } } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Repository/MenuRepository.cs
C#
oos
532
using core._1006apparel.Repository; using inside._1006apparel.Entity; using System.Linq; namespace inside._1006apparel.Repository { public class StaffAccountRepository : EFRepository<StaffAccount>, IStaffAccountRepository { public StaffAccountRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } public StaffAccount GetBy(string Username, string PasswordHashed) { return RepositoryQuery.FirstOrDefault(a => a.Username == Username && a.Password == PasswordHashed); } } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Repository/StaffAccountRepository.cs
C#
oos
552
using core._1006apparel.Repository; using inside._1006apparel.Entity; using System.Linq; namespace inside._1006apparel.Repository { public class StaffRepository : EFRepository<Staff>, IStaffRepository { public StaffRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } public Staff GetBy(long Id) { return RepositoryQuery.FirstOrDefault(a => a.Id == Id); } } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Repository/StaffRepository.cs
C#
oos
442
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("inside.1006apparel.Repository")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("inside.1006apparel.Repository")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ee09eafc-c8b1-47c1-a63e-78ba524f8430")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
1006apparel
trunk/1006apparel.com/inside.1006apparel.Repository/Properties/AssemblyInfo.cs
C#
oos
1,470
using core._1006apparel.Repository; using inside._1006apparel.Entity; using System.Collections.Generic; namespace inside._1006apparel.Repository { public interface IStaffRoleRepository : IRepository<StaffRole> { List<StaffRole> GetBy(long staffId); } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Repository/IStaffRoleRepository.cs
C#
oos
288
using core._1006apparel.Repository; using inside._1006apparel.Entity; namespace inside._1006apparel.Repository { public interface IStaffRepository : IRepository<Staff> { Staff GetBy(long Id); } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Repository/IStaffRepository.cs
C#
oos
230
using core._1006apparel.Repository; using inside._1006apparel.Entity; namespace inside._1006apparel.Repository { public interface IStaffAccountRepository : IRepository<StaffAccount> { StaffAccount GetBy(string Username, string PasswordHashed); } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Repository/IStaffAccountRepository.cs
C#
oos
282
using core._1006apparel.Repository; using inside._1006apparel.Entity; using System.Collections.Generic; using System.Linq; namespace inside._1006apparel.Repository { public class StaffRoleRepository : EFRepository<StaffRole>, IStaffRoleRepository { public StaffRoleRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } public List<StaffRole> GetBy(long staffId) { return RepositoryQuery.Where(a => a.StaffId == staffId).ToList(); } } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Repository/StaffRoleRepository.cs
C#
oos
518
using core._1006apparel.Repository; using inside._1006apparel.Entity; namespace inside._1006apparel.Repository { public interface IRoleRepository : IRepository<Role> { } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Repository/IRoleRepository.cs
C#
oos
197
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("inside.1006apparel.Entity")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("inside.1006apparel.Entity")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("28452fd9-51f2-4663-baa5-1ea513a6c3c9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
1006apparel
trunk/1006apparel.com/inside.1006apparel.Entity/Properties/AssemblyInfo.cs
C#
oos
1,462
using core._1006apparel.Repository; namespace inside._1006apparel.Entity { public partial class inside1006apparelEntities : IObjectContext { public inside1006apparelEntities(string connectionString) : base(connectionString) { var _ = typeof(System.Data.Entity.SqlServer.SqlProviderServices); this.Configuration.LazyLoadingEnabled = false; this.Configuration.ProxyCreationEnabled = false; } } }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Entity/inside1006apparelEntities.cs
C#
oos
495
namespace core._1006apparel.security { public interface _1006apparelIPrincipal { } }
1006apparel
trunk/1006apparel.com/core.1006apparel.security/IPrincipal.cs
C#
oos
106
using System.Collections.Generic; using System.Runtime.Serialization; using System.Security.Principal; namespace core._1006apparel.security { public class _1006apparelPrincipal : _1006apparelIPrincipal, IPrincipal { public _1006apparelPrincipal() { } public IIdentity Identity { get { return _1006apparelIdentity != null ? _1006apparelIdentity : null; } } [DataMember] public _1006apparelIdentity _1006apparelIdentity { get; set; } [DataMember] public SortedSet<MenuModel> Menus { get; set; } [DataMember] public HashSet<string> Roles { get; set; } public bool IsInRole(string role) { return true; } } }
1006apparel
trunk/1006apparel.com/core.1006apparel.security/Principal.cs
C#
oos
766
namespace core._1006apparel.security { public interface _1006apparelIIdentity { } }
1006apparel
trunk/1006apparel.com/core.1006apparel.security/IIdentity.cs
C#
oos
105
namespace core._1006apparel.security { public class Config { public const string cookie_name = "aprss"; public const string identity_authentication_type = "Custom"; } }
1006apparel
trunk/1006apparel.com/core.1006apparel.security/Config.cs
C#
oos
208
using core._1006apparel.utils; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Web; using System.Web.SessionState; namespace core._1006apparel.security { [Serializable] [DataContract] public class _1006apparelSession : IDisposable { private const string _1006apparel_cookie_name = Config.cookie_name; public _1006apparelSession() { } [DataMember] public _1006apparelPrincipal Principal { get; set; } public static _1006apparelSession Current { get { return sessionContext; } } public string Token { get { return requestSessionToken; } } public bool IsAuthenticated { get { return Principal != null && Principal._1006apparelIdentity != null && Principal._1006apparelIdentity.IsAuthenticated; } } public void UpdateSession() { var _session = getSession(); var dict = (Dictionary<string, SessionModel>)_session[_1006apparel_cookie_name]; removeSessionExpired(dict); updateSession(dict); } public void Dispose() { Principal = null; UpdateSession(); } public static void SetExpireAll(long staffId) { var _session = getSession(); var dict = (Dictionary<string, SessionModel>)_session[_1006apparel_cookie_name]; var expiredSession = dict.Where(a => a.Value != null && a.Value.Session != null && a.Value.Session.Principal != null && a.Value.Session.Principal._1006apparelIdentity != null && a.Value.Session.Principal._1006apparelIdentity.Name == staffId.ToString()).ToList(); if (expiredSession == null || expiredSession.Count == 0) { return; } removeSessionExpired(dict, expiredSession); updateSession(dict); } private Dictionary<string, string> Items { get { if (sessionContext.Items == null) { return new Dictionary<string, string>(); } return sessionContext.Items; } } public string GetSession(string key) { if (string.IsNullOrEmpty(key) || !Items.ContainsKey(key)) { return null; } return Items[key]; } public void SetSession(string key, string data) { if (string.IsNullOrEmpty(key)) { return; } Items.Add(key, data); UpdateSession(); } public void RemoveSession(string key) { if (string.IsNullOrEmpty(key) || !Items.ContainsKey(key)) { return; } Items.Remove(key); UpdateSession(); } private static string requestSessionToken { get { if (HttpContext.Current == null || HttpContext.Current.Request == null) { return null; } var request = HttpContext.Current.Request; if (request.Cookies == null || request.Cookies[_1006apparel_cookie_name] == null) { var sessionToken = Guid.NewGuid().ToString("D").ToMD5(); HttpContext.Current.Response.SetCookie(new HttpCookie(_1006apparel_cookie_name, sessionToken)); HttpContext.Current.Response.Cookies[_1006apparel_cookie_name].Expires = DateTime.MinValue; return sessionToken; } return request.Cookies[_1006apparel_cookie_name].Value; } } private static _1006apparelSession sessionContext { get { var _session = getSession(); var dict = (Dictionary<string, SessionModel>)_session[_1006apparel_cookie_name]; _1006apparelSession result; if (!dict.ContainsKey(requestSessionToken) || dict[requestSessionToken].Session == null) { result = new _1006apparelSession(); } else { result = dict[requestSessionToken].Session; } return result; } } private static DateTime getSessionExpiredDate() { return DateTime.UtcNow.AddDays(1); } private static HttpSessionState getSession() { var _session = HttpContext.Current.Session; if (_session[_1006apparel_cookie_name] == null) { _session.Add(_1006apparel_cookie_name, new Dictionary<string, SessionModel>()); } return _session; } private static void updateSession(Dictionary<string, SessionModel> dict) { if (!dict.ContainsKey(requestSessionToken)) { dict.Add(requestSessionToken, new SessionModel() { Session = Current, ExpiredDate = getSessionExpiredDate() }); } else { dict[requestSessionToken] = new SessionModel() { Session = Current, ExpiredDate = getSessionExpiredDate() }; } } private static void removeSessionExpired(Dictionary<string, SessionModel> dict, List<KeyValuePair<string, SessionModel>> expiredSession = null) { if (expiredSession == null) { expiredSession = dict.Where(a => a.Key != requestSessionToken && (a.Value == null || a.Value.ExpiredDate < DateTime.UtcNow)).ToList(); } if (expiredSession != null && expiredSession.Count > 0) { foreach (var session in expiredSession) { dict.Remove(session.Key); } } } private class SessionModel { public _1006apparelSession Session { get; set; } public DateTime ExpiredDate { get; set; } } } }
1006apparel
trunk/1006apparel.com/core.1006apparel.security/Session.cs
C#
oos
6,953
using System; using System.Collections.Generic; namespace core._1006apparel.security { public class MenuModel : IComparable { public MenuModel() { } public long Id { get; set; } public string Name { get; set; } public string Code { get; set; } public string Url { get; set; } public int Sort { get; set; } public SortedSet<MenuModel> Childs { get; set; } public bool IsActived { get; set; } public int CompareTo(object obj) { if (obj.GetType() != typeof(MenuModel)) { return 0; } var objMenu = (MenuModel)obj; return this.Sort.CompareTo(objMenu.Sort); } } }
1006apparel
trunk/1006apparel.com/core.1006apparel.security/MenuModel.cs
C#
oos
792
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("core.1006apparel.security")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("core.1006apparel.security")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0e5af21b-4851-4e7d-bf19-f09f3207287f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
1006apparel
trunk/1006apparel.com/core.1006apparel.security/Properties/AssemblyInfo.cs
C#
oos
1,462
using System.Runtime.Serialization; using System.Security.Principal; namespace core._1006apparel.security { public class _1006apparelIdentity : _1006apparelIIdentity, IIdentity { [DataMember] public string Name { get; set; } [DataMember] public long? StaffId { get; set; } [DataMember] public string StaffFullname { get; set; } [DataMember] public string StaffUsername { get; set; } public _1006apparelIdentity() { } public string AuthenticationType { get { return Config.identity_authentication_type; } } public bool IsAuthenticated { get { return !string.IsNullOrEmpty(Name); } } } }
1006apparel
trunk/1006apparel.com/core.1006apparel.security/Identity.cs
C#
oos
839
using System; using System.Security.Cryptography; using System.Text; namespace core._1006apparel.utils { public static class String { public static byte[] ToByte(this string str) { return Encoding.UTF8.GetBytes(str); } public static string ToMD5(this string str) { var result = string.Empty; using (var md5 = MD5.Create()) { var data = md5.ComputeHash(str.ToByte()); var h = string.Empty; foreach (var b in data) h += b.ToString("x2"); result = h.ToLower(); } return result; } public static string Base64Encode(this string str) { return str.ToByte().ToBase64String(); } public static string Base64Decode(this string str) { return Convert.FromBase64String(str).ToUTF8String(); } } }
1006apparel
trunk/1006apparel.com/core.1006apparel.utils/ExtendObject/String.cs
C#
oos
1,013
using System; using System.Text; namespace core._1006apparel.utils { public static class Binary { public static string ToUTF8String(this byte[] binary) { return Encoding.UTF8.GetString(binary); } public static string ToBase64String(this byte[] binary) { return Convert.ToBase64String(binary); } } }
1006apparel
trunk/1006apparel.com/core.1006apparel.utils/ExtendObject/Binary.cs
C#
oos
406
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("core.1006apparel.utils")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("core.1006apparel.utils")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c8db1431-c904-46f3-8d69-87794746cf39")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
1006apparel
trunk/1006apparel.com/core.1006apparel.utils/Properties/AssemblyInfo.cs
C#
oos
1,456
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Resources; namespace core._1006apparel.utils { public static class ResourceHelper { /// <summary> /// Get a resource string /// </summary> /// <param name="key"></param> /// <param name="resourceType"></param> /// <returns>Empty if there is no resource</returns> public static string Get(string key, Type resourceType) { string val = null; ResourceManager resManager = new ResourceManager(resourceType); val = resManager.GetString(key); return val ?? key; } /// <summary> /// Translate Property of Entity In List From Enum With Display Resource /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="list"></param> /// <param name="expression"></param> /// <param name="enumType"></param> public static void TranslateFromEnum<T, TProperty>(this List<T> list, Expression<Func<T, TProperty>> expression, Type enumType) { string propertyName = expression.GetPropertyName(); Type type = typeof(T); PropertyInfo pInfo = type.GetProperty(propertyName); Dictionary<string, string> dicValues = EnumToDictionary(enumType); foreach (var obj in list) { object keyobj = pInfo.GetValue(obj, null); string key = keyobj == null ? null : keyobj.ToString(); if (key != null && dicValues.ContainsKey(key)) pInfo.SetValue(obj, dicValues[key], null); } } /// <summary> /// Translate Property of Entity In List From Enum With Display Resource /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="list"></param> /// <param name="expression"></param> /// <param name="enumType"></param> public static void TranslateFromEnum<T, TProperty>(this List<T> list, Expression<Func<T, TProperty>> fromExpression, Expression<Func<T, TProperty>> toExpression, Type enumType) { string fromPropertyName = fromExpression.GetPropertyName(); string toPropertyName = toExpression.GetPropertyName(); Type type = typeof(T); PropertyInfo pFromInfo = type.GetProperty(fromPropertyName); PropertyInfo pToInfo = type.GetProperty(toPropertyName); Dictionary<string, string> dicValues = EnumToDictionary(enumType); foreach (var obj in list) { object keyobj = pFromInfo.GetValue(obj, null); string key = keyobj == null ? null : keyobj.ToString(); if (key != null && dicValues.ContainsKey(key)) pToInfo.SetValue(obj, dicValues[key], null); } } public static string DisplayForEnumValue(Object value) { Type enumType = value.GetType(); var fieldInfo = enumType.GetField(value.ToString()); if (fieldInfo != null) { DisplayAttribute displayAtt = fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute; return displayAtt.GetName(); } else { return string.Format("Can't Get Display Text From Enum {0} With Value = {1}", enumType.Name, value); } } /// <summary> /// Convert Enum To Dictionary (Key = Enum Field, Value = Resource Display) /// </summary> /// <param name="enumType"></param> /// <returns></returns> public static Dictionary<string, string> EnumToDictionary(Type enumType) { Dictionary<string, string> listEnumField = new Dictionary<string, string>(); Type type = enumType; foreach (var evalue in type.GetEnumValues()) { var valueName = type.GetField(evalue.ToString()); string displayLabel = ""; DisplayAttribute displayAtt = valueName.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute; if (displayAtt != null) displayLabel = displayAtt.GetName(); listEnumField.Add(evalue.ToString(), displayLabel); } return listEnumField; } public static Dictionary<object, string> EnumToArray(Type enumType) { Dictionary<object, string> listEnumField = new Dictionary<object, string>(); Type type = enumType; foreach (var evalue in type.GetEnumValues()) { var valueName = type.GetField(evalue.ToString()); string displayLabel = ""; DisplayAttribute displayAtt = valueName.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute; if (displayAtt != null) displayLabel = displayAtt.GetName(); listEnumField.Add(evalue, displayLabel); } return listEnumField; } } }
1006apparel
trunk/1006apparel.com/core.1006apparel.utils/ResourceHelper.cs
C#
oos
5,600
using System; using System.Linq; using System.Linq.Expressions; namespace core._1006apparel.utils { public static class ExpressionHelper { public static string GetPropertyName<T, TProperty>(this Expression<Func<T, TProperty>> expression) { MemberExpression member = null; if (expression.Body is UnaryExpression) { UnaryExpression express = (UnaryExpression)expression.Body; member = (MemberExpression)express.Operand; } if (expression.Body is MemberExpression) { member = expression.Body as MemberExpression; } if (member == null) throw new InvalidOperationException("Expression must be a member expression"); string propertyName = member.Member.Name; return propertyName; } /// <summary> /// And 2 boolean expression /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expressionOne"></param> /// <param name="expressionTwo"></param> /// <returns></returns> public static Expression<Func<T, Boolean>> And<T>(this Expression<Func<T, Boolean>> expressionOne, Expression<Func<T, Boolean>> expressionTwo) { var invokedSecond = Expression.Invoke(expressionTwo, expressionOne.Parameters.Cast<Expression>()); return Expression.Lambda<Func<T, Boolean>>(Expression.And(expressionOne.Body, invokedSecond), expressionOne.Parameters); } /// <summary> /// Or 2 boolean expression /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expressionOne"></param> /// <param name="expressionTwo"></param> /// <returns></returns> public static Expression<Func<T, Boolean>> Or<T>(this Expression<Func<T, Boolean>> expressionOne, Expression<Func<T, Boolean>> expressionTwo) { var invokedSecond = Expression.Invoke(expressionTwo, expressionOne.Parameters.Cast<Expression>()); return Expression.Lambda<Func<T, Boolean>>(Expression.Or(expressionOne.Body, invokedSecond), expressionOne.Parameters); } } }
1006apparel
trunk/1006apparel.com/core.1006apparel.utils/ExpressionHelper.cs
C#
oos
2,314
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
1006apparel
trunk/1006apparel.com/inside.1006apparel.Web/Views/_ViewStart.cshtml
HTML+Razor
oos
55
<div ng-if="$location.path() === '/menu' && !$templateInited.contains('/menu')"> @Scripts.Render("~/scripts/modules/menu.js") {{ $initTemplate('/menu') }} </div> <div ng-if="$location.path() === '/staff' && !$templateInited.contains('/staff')"> @Scripts.Render("~/scripts/modules/staff.js") {{ $initTemplate('/staff') }} </div>
1006apparel
trunk/1006apparel.com/inside.1006apparel.Web/Views/Route/Index.cshtml
HTML+Razor
oos
355
@{ Layout = "~/Views/Shared/_Root.cshtml"; } @section css{ @Styles.Render("~/bundles/pages/layoutcss") @RenderSection("css", required: false) } <div data-ng-app="1006apparel"> <div data-ng-controller="RouteController"> <div class="page-boxed page-header-fixed page-sidebar-closed-hide-logo page-container-bg-solid page-sidebar-closed-hide-logo"> <div class="page-header navbar navbar-fixed-top"> <div class="page-header-inner container"> @Html.Action("_LayoutPageHeader", "Home") </div> <!-- END HEADER INNER --> </div> <div class="clearfix"></div> <div class="container"> <!-- BEGIN CONTAINER --> <div class="page-container"> <!-- BEGIN SIDEBAR --> <div class="page-sidebar-wrapper"> @Html.Action("_LayoutPageSidebar", "Home") </div> <div class="page-content-wrapper"> <div class="page-content"> <div data-ng-view></div> </div> </div> </div> </div> </div> @Scripts.Render("~/bundles/commonjs") @Scripts.Render("~/bundles/modules/routejs") @RenderBody() @RenderSection("scripts", required: false) </div> </div>
1006apparel
trunk/1006apparel.com/inside.1006apparel.Web/Views/Shared/_Layout.cshtml
HTML+Razor
oos
1,496
@{ Layout = null; } <div class="page-logo"> <a href="/"> <img src="/logo.png" alt="logo" class="logo-default"> </a> <div class="menu-toggler sidebar-toggler"> </div> </div> <!-- BEGIN RESPONSIVE MENU TOGGLER --> <a href="javascript:;" class="menu-toggler responsive-toggler" data-toggle="collapse" data-target=".navbar-collapse"> </a> <!-- END RESPONSIVE MENU TOGGLER --> <!-- BEGIN PAGE ACTIONS --> <!-- DOC: Remove "hide" class to enable the page header actions --> <div class="page-actions hide"> <div class="btn-group"> <button type="button" class="btn btn-circle red-pink dropdown-toggle" data-toggle="dropdown"> <i class="icon-bar-chart"></i>&nbsp;<span class="hidden-sm hidden-xs">New&nbsp;</span>&nbsp;<i class="fa fa-angle-down"></i> </button> <ul class="dropdown-menu" role="menu"> <li> <a href="#"> <i class="icon-user"></i> New User </a> </li> <li> <a href="#"> <i class="icon-present"></i> New Event <span class="badge badge-success">4</span> </a> </li> <li> <a href="#"> <i class="icon-basket"></i> New order </a> </li> <li class="divider"> </li> <li> <a href="#"> <i class="icon-flag"></i> Pending Orders <span class="badge badge-danger">4</span> </a> </li> <li> <a href="#"> <i class="icon-users"></i> Pending Users <span class="badge badge-warning">12</span> </a> </li> </ul> </div> <div class="btn-group"> <button type="button" class="btn btn-circle green-haze dropdown-toggle" data-toggle="dropdown"> <i class="icon-bell"></i>&nbsp;<span class="hidden-sm hidden-xs">Post&nbsp;</span>&nbsp;<i class="fa fa-angle-down"></i> </button> <ul class="dropdown-menu" role="menu"> <li> <a href="#"> <i class="icon-docs"></i> New Post </a> </li> <li> <a href="#"> <i class="icon-tag"></i> New Comment </a> </li> <li> <a href="#"> <i class="icon-share"></i> Share </a> </li> <li class="divider"> </li> <li> <a href="#"> <i class="icon-flag"></i> Comments <span class="badge badge-success">4</span> </a> </li> <li> <a href="#"> <i class="icon-users"></i> Feedbacks <span class="badge badge-danger">2</span> </a> </li> </ul> </div> </div> <!-- END PAGE ACTIONS --> <!-- BEGIN PAGE TOP --> <div class="page-top"> <!-- BEGIN HEADER SEARCH BOX --> <!-- DOC: Apply "search-form-expanded" right after the "search-form" class to have half expanded search box --> <form class="search-form search-form-expanded" action="extra_search.html" method="GET"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search..." name="query"> <span class="input-group-btn"> <a href="javascript:;" class="btn submit"><i class="icon-magnifier"></i></a> </span> </div> </form> <!-- END HEADER SEARCH BOX --> <!-- BEGIN TOP NAVIGATION MENU --> <div class="top-menu"> <ul class="nav navbar-nav pull-right"> <!-- BEGIN NOTIFICATION DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-notification" id="header_notification_bar"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-bell"></i> <span class="badge badge-default"> 7 </span> </a> <ul class="dropdown-menu"> <li class="external"> <h3><span class="bold">12 pending</span> notifications</h3> <a href="extra_profile.html">view all</a> </li> <li> <div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 250px;"> <ul class="dropdown-menu-list scroller" style="height: 250px; overflow: hidden; width: auto;" data-handle-color="#637283" data-initialized="1"> <li> <a href="javascript:;"> <span class="time">just now</span> <span class="details"> <span class="label label-sm label-icon label-success"> <i class="fa fa-plus"></i> </span> New user registered. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 mins</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Server #12 overloaded. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">10 mins</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Server #2 not responding. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">14 hrs</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> Application error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">2 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Database overloaded 68%. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> A user IP blocked. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">4 days</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Storage Server #4 not responding dfdfdfd. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">5 days</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> System Error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">9 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Storage server failed. </span> </a> </li> </ul><div class="slimScrollBar" style="width: 7px; position: absolute; top: 0px; opacity: 0.4; display: block; border-radius: 7px; z-index: 99; right: 1px; background: rgb(99, 114, 131);"></div><div class="slimScrollRail" style="width: 7px; height: 100%; position: absolute; top: 0px; display: none; border-radius: 7px; opacity: 0.2; z-index: 90; right: 1px; background: rgb(234, 234, 234);"></div> </div> </li> </ul> </li> <!-- END NOTIFICATION DROPDOWN --> <!-- BEGIN INBOX DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-inbox" id="header_inbox_bar"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-envelope-open"></i> <span class="badge badge-default"> 4 </span> </a> <ul class="dropdown-menu"> <li class="external"> <h3>You have <span class="bold">7 New</span> Messages</h3> <a href="page_inbox.html">view all</a> </li> <li> <div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 275px;"> <ul class="dropdown-menu-list scroller" style="height: 275px; overflow: hidden; width: auto;" data-handle-color="#637283" data-initialized="1"> <li> <a href="inbox.html?a=view"> <span class="photo"> @*<img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt="">*@ </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">Just Now </span> </span> <span class="message"> Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> </ul><div class="slimScrollBar" style="width: 7px; position: absolute; top: 0px; opacity: 0.4; display: block; border-radius: 7px; z-index: 99; right: 1px; background: rgb(99, 114, 131);"></div><div class="slimScrollRail" style="width: 7px; height: 100%; position: absolute; top: 0px; display: none; border-radius: 7px; opacity: 0.2; z-index: 90; right: 1px; background: rgb(234, 234, 234);"></div> </div> </li> </ul> </li> <!-- END INBOX DROPDOWN --> <!-- BEGIN TODO DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-tasks" id="header_task_bar"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-calendar"></i> <span class="badge badge-default"> 3 </span> </a> <ul class="dropdown-menu extended tasks"> <li class="external"> <h3>You have <span class="bold">12 pending</span> tasks</h3> <a href="page_todo.html">view all</a> </li> <li> <div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 275px;"> <ul class="dropdown-menu-list scroller" style="height: 275px; overflow: hidden; width: auto;" data-handle-color="#637283" data-initialized="1"> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New release v1.2 </span> <span class="percent">30%</span> </span> <span class="progress"> <span style="width: 40%;" class="progress-bar progress-bar-success" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">40% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Application deployment</span> <span class="percent">65%</span> </span> <span class="progress"> <span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">65% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile app release</span> <span class="percent">98%</span> </span> <span class="progress"> <span style="width: 98%;" class="progress-bar progress-bar-success" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">98% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Database migration</span> <span class="percent">10%</span> </span> <span class="progress"> <span style="width: 10%;" class="progress-bar progress-bar-warning" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">10% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Web server upgrade</span> <span class="percent">58%</span> </span> <span class="progress"> <span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">58% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile development</span> <span class="percent">85%</span> </span> <span class="progress"> <span style="width: 85%;" class="progress-bar progress-bar-success" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">85% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New UI release</span> <span class="percent">38%</span> </span> <span class="progress progress-striped"> <span style="width: 38%;" class="progress-bar progress-bar-important" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">38% Complete</span></span> </span> </a> </li> </ul><div class="slimScrollBar" style="width: 7px; position: absolute; top: 0px; opacity: 0.4; display: block; border-radius: 7px; z-index: 99; right: 1px; background: rgb(99, 114, 131);"></div><div class="slimScrollRail" style="width: 7px; height: 100%; position: absolute; top: 0px; display: none; border-radius: 7px; opacity: 0.2; z-index: 90; right: 1px; background: rgb(234, 234, 234);"></div> </div> </li> </ul> </li> <!-- END TODO DROPDOWN --> <!-- BEGIN USER LOGIN DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-user"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> @*<img alt="" class="img-circle" src="../../assets/admin/layout2/img/avatar3_small.jpg">*@ <span class="username username-hide-on-mobile"> @core._1006apparel.security._1006apparelSession.Current.Principal._1006apparelIdentity.StaffFullname </span> <i class="fa fa-angle-down"></i> </a> <ul class="dropdown-menu dropdown-menu-default"> <li> <a href="extra_profile.html"> <i class="icon-user"></i> My Profile </a> </li> <li> <a href="page_calendar.html"> <i class="icon-calendar"></i> My Calendar </a> </li> <li> <a href="inbox.html"> <i class="icon-envelope-open"></i> My Inbox <span class="badge badge-danger"> 3 </span> </a> </li> <li> <a href="page_todo.html"> <i class="icon-rocket"></i> My Tasks <span class="badge badge-success"> 7 </span> </a> </li> <li class="divider"> </li> <li> <a href="extra_lock.html"> <i class="icon-lock"></i> Lock Screen </a> </li> <li> <a href="~/auth/logout"> <i class="icon-key"></i> Đăng xuất </a> </li> </ul> </li> <!-- END USER LOGIN DROPDOWN --> </ul> </div> <!-- END TOP NAVIGATION MENU --> </div> <!-- END PAGE TOP -->
1006apparel
trunk/1006apparel.com/inside.1006apparel.Web/Views/Shared/Components/_LayoutPageHeader.cshtml
HTML+Razor
oos
24,113
@{ Layout = null; } @{ var menus = core._1006apparel.security._1006apparelSession.Current.Principal.Menus; } <!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing --> <!-- DOC: Change data-auto-speed="200" to adjust the sub menu slide up/down speed --> <div class="page-sidebar navbar-collapse collapse"> <!-- BEGIN SIDEBAR MENU --> <!-- DOC: Apply "page-sidebar-menu-light" class right after "page-sidebar-menu" to enable light sidebar menu style(without borders) --> <!-- DOC: Apply "page-sidebar-menu-hover-submenu" class right after "page-sidebar-menu" to enable hoverable(hover vs accordion) sub menu mode --> <!-- DOC: Apply "page-sidebar-menu-closed" class right after "page-sidebar-menu" to collapse("page-sidebar-closed" class must be applied to the body element) the sidebar sub menu mode --> <!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing --> <!-- DOC: Set data-keep-expand="true" to keep the submenues expanded --> <!-- DOC: Set data-auto-speed="200" to adjust the sub menu slide up/down speed --> <ul class="page-sidebar-menu page-sidebar-menu-hover-submenu" data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200"> @if (menus != null && menus.Count > 0) { foreach (var menu in menus) { <li> <a href="@Url.Content(menu.Url)"> <i class="@menu.Code"></i> <span class="title">@menu.Name</span> </a> </li> } } </ul> </div>
1006apparel
trunk/1006apparel.com/inside.1006apparel.Web/Views/Shared/Components/_LayoutPageSidebar.cshtml
HTML+Razor
oos
1,687
@{ ViewBag.Title = "Không được quyền truy cập"; } <div class="mt200 text-center"> <h3>Bạn không được quyền truy cập trang này</h3> </div>
1006apparel
trunk/1006apparel.com/inside.1006apparel.Web/Views/Shared/_DontHaveAccess.cshtml
HTML+Razor
oos
176
<div data-ng-controller="StaffController"> staff <h2>{{ title }}</h2> </div>
1006apparel
trunk/1006apparel.com/inside.1006apparel.Web/Views/Shared/Modules/Staff/Index.cshtml
HTML+Razor
oos
92