PageRenderTime 42ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/pastebin/pastebin.py

https://bitbucket.org/stavrossk/maraschino
Python | 792 lines | 622 code | 65 blank | 105 comment | 21 complexity | 279db8dd70a1f5f56ccff7df86f39898 MD5 | raw file
  1. #!/usr/bin/env python
  2. #############################################################################
  3. # Pastebin.py - Python 3.2 Pastebin API.
  4. # Copyright (C) 2012 Ian Havelock
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. #############################################################################
  20. # This software is a derivative work of:
  21. # http://winappdbg.sourceforge.net/blog/pastebin.py
  22. #############################################################################
  23. __ALL__ = ['delete_paste', 'user_details', 'trending', 'pastes_by_user', 'generate_user_key',
  24. 'legacy_paste', 'paste', 'Pastebin', 'PastebinError']
  25. import sys
  26. import urllib
  27. class PastebinError(RuntimeError):
  28. """Pastebin API error.
  29. The error message returned by the web application is stored as the Python exception message."""
  30. class PastebinAPI(object):
  31. """Pastebin API interaction object.
  32. Public functions:
  33. paste -- Pastes a user-specified file or string using the new API-key POST method.
  34. legacy_paste -- Pastes a user-specified file or string using the old anonymous POST method.
  35. generate_user_key -- Generates a session-key that is required for other functions.
  36. pastes_by_user -- Returns all public pastes submitted by the specified login credentials.
  37. trending -- Returns the top trending paste.
  38. user_details -- Returns details about the user for the specified API user key.
  39. delete_paste -- Adds two numbers together and returns the result."""
  40. # String to determine bad API requests
  41. _bad_request = 'Bad API request'
  42. # Base domain name
  43. _base_domain = 'pastebin.com'
  44. # Valid Pastebin URLs begin with this string (kinda bvious)
  45. _prefix_url = 'http://%s/' % _base_domain
  46. # Valid Pastebin URLs with a custom subdomain begin with this string
  47. _subdomain_url = 'http://%%s.%s/' % _base_domain
  48. # URL to the LEGACY POST API
  49. _legacy_api_url= 'http://%s/api_public.php' % _base_domain
  50. # URL to the POST API
  51. _api_url= 'http://%s/api/api_post.php' % _base_domain
  52. # URL to the login POST API
  53. _api_login_url= 'http://%s/api/api_login.php' % _base_domain
  54. # Valid paste_expire_date values (Never, 10 minutes, 1 Hour, 1 Day, 1 Month)
  55. paste_expire_date = ('N', '10M', '1H', '1D', '1M')
  56. # Valid paste_expire_date values (0 = public, 1 = unlisted, 2 = private)
  57. paste_private = ('public', 'unlisted', 'private')
  58. # Valid parse_format values
  59. paste_format = (
  60. '4cs', # 4CS
  61. '6502acme', # 6502 ACME Cross Assembler
  62. '6502kickass', # 6502 Kick Assembler
  63. '6502tasm', # 6502 TASM/64TASS
  64. 'abap', # ABAP
  65. 'actionscript', # ActionScript
  66. 'actionscript3', # ActionScript 3
  67. 'ada', # Ada
  68. 'algol68', # ALGOL 68
  69. 'apache', # Apache Log
  70. 'applescript', # AppleScript
  71. 'apt_sources', # APT Sources
  72. 'asm', # ASM (NASM)
  73. 'asp', # ASP
  74. 'autoconf', # autoconf
  75. 'autohotkey', # Autohotkey
  76. 'autoit', # AutoIt
  77. 'avisynth', # Avisynth
  78. 'awk', # Awk
  79. 'bascomavr', # BASCOM AVR
  80. 'bash', # Bash
  81. 'basic4gl', # Basic4GL
  82. 'bibtex', # BibTeX
  83. 'blitzbasic', # Blitz Basic
  84. 'bnf', # BNF
  85. 'boo', # BOO
  86. 'bf', # BrainFuck
  87. 'c', # C
  88. 'c_mac', # C for Macs
  89. 'cil', # C Intermediate Language
  90. 'csharp', # C#
  91. 'cpp', # C++
  92. 'cpp-qt', # C++ (with QT extensions)
  93. 'c_loadrunner', # C: Loadrunner
  94. 'caddcl', # CAD DCL
  95. 'cadlisp', # CAD Lisp
  96. 'cfdg', # CFDG
  97. 'chaiscript', # ChaiScript
  98. 'clojure', # Clojure
  99. 'klonec', # Clone C
  100. 'klonecpp', # Clone C++
  101. 'cmake', # CMake
  102. 'cobol', # COBOL
  103. 'coffeescript', # CoffeeScript
  104. 'cfm', # ColdFusion
  105. 'css', # CSS
  106. 'cuesheet', # Cuesheet
  107. 'd', # D
  108. 'dcs', # DCS
  109. 'delphi', # Delphi
  110. 'oxygene', # Delphi Prism (Oxygene)
  111. 'diff', # Diff
  112. 'div', # DIV
  113. 'dos', # DOS
  114. 'dot', # DOT
  115. 'e', # E
  116. 'ecmascript', # ECMAScript
  117. 'eiffel', # Eiffel
  118. 'email', # Email
  119. 'epc', # EPC
  120. 'erlang', # Erlang
  121. 'fsharp', # F#
  122. 'falcon', # Falcon
  123. 'fo', # FO Language
  124. 'f1', # Formula One
  125. 'fortran', # Fortran
  126. 'freebasic', # FreeBasic
  127. 'freeswitch', # FreeSWITCH
  128. 'gambas', # GAMBAS
  129. 'gml', # Game Maker
  130. 'gdb', # GDB
  131. 'genero', # Genero
  132. 'genie', # Genie
  133. 'gettext', # GetText
  134. 'go', # Go
  135. 'groovy', # Groovy
  136. 'gwbasic', # GwBasic
  137. 'haskell', # Haskell
  138. 'hicest', # HicEst
  139. 'hq9plus', # HQ9 Plus
  140. 'html4strict', # HTML
  141. 'html5', # HTML 5
  142. 'icon', # Icon
  143. 'idl', # IDL
  144. 'ini', # INI file
  145. 'inno', # Inno Script
  146. 'intercal', # INTERCAL
  147. 'io', # IO
  148. 'j', # J
  149. 'java', # Java
  150. 'java5', # Java 5
  151. 'javascript', # JavaScript
  152. 'jquery', # jQuery
  153. 'kixtart', # KiXtart
  154. 'latex', # Latex
  155. 'lb', # Liberty BASIC
  156. 'lsl2', # Linden Scripting
  157. 'lisp', # Lisp
  158. 'llvm', # LLVM
  159. 'locobasic', # Loco Basic
  160. 'logtalk', # Logtalk
  161. 'lolcode', # LOL Code
  162. 'lotusformulas', # Lotus Formulas
  163. 'lotusscript', # Lotus Script
  164. 'lscript', # LScript
  165. 'lua', # Lua
  166. 'm68k', # M68000 Assembler
  167. 'magiksf', # MagikSF
  168. 'make', # Make
  169. 'mapbasic', # MapBasic
  170. 'matlab', # MatLab
  171. 'mirc', # mIRC
  172. 'mmix', # MIX Assembler
  173. 'modula2', # Modula 2
  174. 'modula3', # Modula 3
  175. '68000devpac', # Motorola 68000 HiSoft Dev
  176. 'mpasm', # MPASM
  177. 'mxml', # MXML
  178. 'mysql', # MySQL
  179. 'newlisp', # newLISP
  180. 'text', # None
  181. 'nsis', # NullSoft Installer
  182. 'oberon2', # Oberon 2
  183. 'objeck', # Objeck Programming Langua
  184. 'objc', # Objective C
  185. 'ocaml-brief', # OCalm Brief
  186. 'ocaml', # OCaml
  187. 'pf', # OpenBSD PACKET FILTER
  188. 'glsl', # OpenGL Shading
  189. 'oobas', # Openoffice BASIC
  190. 'oracle11', # Oracle 11
  191. 'oracle8', # Oracle 8
  192. 'oz', # Oz
  193. 'pascal', # Pascal
  194. 'pawn', # PAWN
  195. 'pcre', # PCRE
  196. 'per', # Per
  197. 'perl', # Perl
  198. 'perl6', # Perl 6
  199. 'php', # PHP
  200. 'php-brief', # PHP Brief
  201. 'pic16', # Pic 16
  202. 'pike', # Pike
  203. 'pixelbender', # Pixel Bender
  204. 'plsql', # PL/SQL
  205. 'postgresql', # PostgreSQL
  206. 'povray', # POV-Ray
  207. 'powershell', # Power Shell
  208. 'powerbuilder', # PowerBuilder
  209. 'proftpd', # ProFTPd
  210. 'progress', # Progress
  211. 'prolog', # Prolog
  212. 'properties', # Properties
  213. 'providex', # ProvideX
  214. 'purebasic', # PureBasic
  215. 'pycon', # PyCon
  216. 'python', # Python
  217. 'q', # q/kdb+
  218. 'qbasic', # QBasic
  219. 'rsplus', # R
  220. 'rails', # Rails
  221. 'rebol', # REBOL
  222. 'reg', # REG
  223. 'robots', # Robots
  224. 'rpmspec', # RPM Spec
  225. 'ruby', # Ruby
  226. 'gnuplot', # Ruby Gnuplot
  227. 'sas', # SAS
  228. 'scala', # Scala
  229. 'scheme', # Scheme
  230. 'scilab', # Scilab
  231. 'sdlbasic', # SdlBasic
  232. 'smalltalk', # Smalltalk
  233. 'smarty', # Smarty
  234. 'sql', # SQL
  235. 'systemverilog', # SystemVerilog
  236. 'tsql', # T-SQL
  237. 'tcl', # TCL
  238. 'teraterm', # Tera Term
  239. 'thinbasic', # thinBasic
  240. 'typoscript', # TypoScript
  241. 'unicon', # Unicon
  242. 'uscript', # UnrealScript
  243. 'vala', # Vala
  244. 'vbnet', # VB.NET
  245. 'verilog', # VeriLog
  246. 'vhdl', # VHDL
  247. 'vim', # VIM
  248. 'visualprolog', # Visual Pro Log
  249. 'vb', # VisualBasic
  250. 'visualfoxpro', # VisualFoxPro
  251. 'whitespace', # WhiteSpace
  252. 'whois', # WHOIS
  253. 'winbatch', # Winbatch
  254. 'xbasic', # XBasic
  255. 'xml', # XML
  256. 'xorg_conf', # Xorg Config
  257. 'xpp', # XPP
  258. 'yaml', # YAML
  259. 'z80', # Z80 Assembler
  260. 'zxbasic', # ZXBasic
  261. )
  262. def __init__(self):
  263. pass
  264. def delete_paste(self, api_dev_key, api_user_key, api_paste_key):
  265. """Delete the paste specified by the api_paste_key.
  266. Usage Example::
  267. >>> from pastebin import PastebinAPI
  268. >>> x = PastebinAPI()
  269. >>> paste_to_delete = x.delete_paste('453a994e0e2f1efae07f8759e59e075b',
  270. ... 'c57a18e6c0ae228cd4bd16fe36da381a',
  271. ... 'WkgcTFtv')
  272. >>> print paste_to_delete
  273. Paste Removed
  274. @type api_dev_key: string
  275. @param api_dev_key: The API Developer Key of a registered U{http://pastebin.com} account.
  276. @type api_user_key: string
  277. @param api_user_key: The API User Key of a U{http://pastebin.com} registered user.
  278. @type api_paste_key: string
  279. @param api_paste_key: The Paste Key of the paste to be deleted (string after final / in U{http://pastebin.com} URL).
  280. @rtype: string
  281. @returns: A successful deletion returns 'Paste Removed'.
  282. """
  283. # Valid api developer key
  284. argv = {'api_dev_key' : str(api_dev_key) }
  285. # Requires pre-registered account
  286. if api_user_key is not None:
  287. argv['api_user_key'] = str(api_user_key)
  288. # Key of the paste to be deleted.
  289. if api_paste_key is not None:
  290. argv['api_paste_key'] = str(api_paste_key)
  291. # Valid API option - 'user_details' in this instance
  292. argv['api_option'] = str('delete')
  293. # lets try to read the URL that we've just built.
  294. request = urllib.urlopen(self._api_url, urllib.urlencode(argv))
  295. response = self._submit_paste(request)
  296. return response
  297. def user_details(self, api_dev_key, api_user_key):
  298. """Return user details of the user specified by the api_user_key.
  299. Usage Example::
  300. >>> from pastebin import PastebinAPI
  301. >>> x = PastebinAPI()
  302. >>> details = x.user_details('453a994e0e2f1efae07f8759e59e075b',
  303. ... 'c57a18e6c0ae228cd4bd16fe36da381a')
  304. >>> print details
  305. <user>
  306. <user_name>MonkeyPuzzle</user_name>
  307. <user_format_short>python</user_format_short>
  308. <user_expiration>N</user_expiration>
  309. <user_avatar_url>http://pastebin.com/i/guest.gif</user_avatar_url>
  310. <user_private>0</user_private>
  311. <user_website></user_website>
  312. <user_email>user@email.com</user_email>
  313. <user_location></user_location>
  314. <user_account_type>0</user_account_type>
  315. </user>
  316. @type api_dev_key: string
  317. @param api_dev_key: The API Developer Key of a registered U{http://pastebin.com} account.
  318. @type api_user_key: string
  319. @param api_user_key: The API User Key of a U{http://pastebin.com} registered user.
  320. @rtype: string
  321. @returns: Returns an XML string containing user information.
  322. """
  323. # Valid api developer key
  324. argv = {'api_dev_key' : str(api_dev_key) }
  325. # Requires pre-registered account to generate an api_user_key (see generate_user_key)
  326. if api_user_key is not None:
  327. argv['api_user_key'] = str(api_user_key)
  328. # Valid API option - 'user_details' in this instance
  329. argv['api_option'] = str('userdetails')
  330. # lets try to read the URL that we've just built.
  331. request_string = urllib.urlopen(self._api_url, urllib.urlencode(argv))
  332. response = request_string.read()
  333. # do some basic error checking here so we can gracefully handle any errors we are likely to encounter
  334. if response.startswith(self._bad_request):
  335. raise PastebinError(response)
  336. elif not response.startswith('<user>'):
  337. raise PastebinError(response)
  338. return response
  339. def trending(self, api_dev_key):
  340. """Returns the top trending paste details.
  341. Usage Example::
  342. >>> from pastebin import PastebinAPI
  343. >>> x = PastebinAPI()
  344. >>> details = x.trending('453a994e0e2f1efae07f8759e59e075b')
  345. >>> print details
  346. <paste>
  347. <paste_key>jjMRFDH6</paste_key>
  348. <paste_date>1333230838</paste_date>
  349. <paste_title></paste_title>
  350. <paste_size>6416</paste_size>
  351. <paste_expire_date>0</paste_expire_date>
  352. <paste_private>0</paste_private>
  353. <paste_format_long>None</paste_format_long>
  354. <paste_format_short>text</paste_format_short>
  355. <paste_url>http://pastebin.com/jjMRFDH6</paste_url>
  356. <paste_hits>6384</paste_hits>
  357. </paste>
  358. Note: Returns multiple trending pastes, not just 1.
  359. @type api_dev_key: string
  360. @param api_dev_key: The API Developer Key of a registered U{http://pastebin.com} account.
  361. @rtype: string
  362. @return: Returns the string (XML formatted) containing the top trending pastes.
  363. """
  364. # Valid api developer key
  365. argv = {'api_dev_key' : str(api_dev_key) }
  366. # Valid API option - 'trends' is returns trending pastes
  367. argv['api_option'] = str('trends')
  368. # lets try to read the URL that we've just built.
  369. request_string = urllib.urlopen(self._api_url, urllib.urlencode(argv))
  370. response = request_string.read()
  371. # do some basic error checking here so we can gracefully handle any errors we are likely to encounter
  372. if response.startswith(self._bad_request):
  373. raise PastebinError(response)
  374. elif not response.startswith('<paste>'):
  375. raise PastebinError(response)
  376. return response
  377. def pastes_by_user(self, api_dev_key, api_user_key, results_limit = None):
  378. """Returns all pastes for the provided api_user_key.
  379. Usage Example::
  380. >>> from pastebin import PastebinAPI
  381. >>> x = PastebinAPI()
  382. >>> details = x.user_details('453a994e0e2f1efae07f8759e59e075b',
  383. ... 'c57a18e6c0ae228cd4bd16fe36da381a',
  384. ... 100)
  385. >>> print details
  386. <paste>
  387. <paste_key>DLiSspYT</paste_key>
  388. <paste_date>1332714730</paste_date>
  389. <paste_title>Pastebin.py - Python 3.2 Pastebin.com API</paste_title>
  390. <paste_size>25300</paste_size>
  391. <paste_expire_date>0</paste_expire_date>
  392. <paste_private>0</paste_private>
  393. <paste_format_long>Python</paste_format_long>
  394. <paste_format_short>python</paste_format_short>
  395. <paste_url>http://pastebin.com/DLiSspYT</paste_url>
  396. <paste_hits>70</paste_hits>
  397. </paste>
  398. Note: Returns multiple pastes, not just 1.
  399. @type api_dev_key: string
  400. @param api_dev_key: The API Developer Key of a registered U{http://pastebin.com} account.
  401. @type api_user_key: string
  402. @param api_user_key: The API User Key of a U{http://pastebin.com} registered user.
  403. @type results_limit: number
  404. @param results_limit: The number of pastes to return between 1 - 1000.
  405. @rtype: string
  406. @returns: Returns an XML string containing number of specified pastes by user.
  407. """
  408. # Valid api developer key
  409. argv = {'api_dev_key' : str(api_dev_key) }
  410. # Requires pre-registered account
  411. if api_user_key is not None:
  412. argv['api_user_key'] = str(api_user_key)
  413. # Number of results to return - between 1 & 1000, default = 50
  414. if results_limit is None:
  415. argv['api_results_limit'] = 50
  416. if results_limit is not None:
  417. if results_limit < 1:
  418. argv['api_results_limit'] = 50
  419. elif results_limit > 1000:
  420. argv['api_results_limit'] = 1000
  421. else:
  422. argv['api_results_limit'] = int(results_limit)
  423. # Valid API option - 'paste' is default for new paste
  424. argv['api_option'] = str('list')
  425. # lets try to read the URL that we've just built.
  426. request_string = urllib.urlopen(self._api_url, urllib.urlencode(argv))
  427. response = request_string.read()
  428. # do some basic error checking here so we can gracefully handle any errors we are likely to encounter
  429. if response.startswith(self._bad_request):
  430. raise PastebinError(response)
  431. elif not response.startswith('<paste>'):
  432. raise PastebinError(response)
  433. return response
  434. def generate_user_key(self, api_dev_key, username, password):
  435. """Generate a user session key - needed for other functions.
  436. Usage Example::
  437. >>> from pastebin import PastebinAPI
  438. >>> x = PastebinAPI()
  439. >>> my_key = x.generate_user_key('453a994e0e2f1efae07f8759e59e075b',
  440. ... 'MonkeyPuzzle',
  441. ... '12345678')
  442. >>> print my_key
  443. c57a18e6c0ae228cd4bd16fe36da381a
  444. @type api_dev_key: string
  445. @param api_dev_key: The API Developer Key of a registered U{http://pastebin.com} account.
  446. @type username: string
  447. @param username: The username of a registered U{http://pastebin.com} account.
  448. @type password: string
  449. @param password: The password of a registered U{http://pastebin.com} account.
  450. @rtype: string
  451. @returns: Session key (api_user_key) to allow authenticated interaction to the API.
  452. """
  453. # Valid api developer key
  454. argv = {'api_dev_key' : str(api_dev_key) }
  455. # Requires pre-registered pastebin account
  456. if username is not None:
  457. argv['api_user_name'] = str(username)
  458. # Requires pre-registered pastebin account
  459. if password is not None:
  460. argv['api_user_password'] = str(password)
  461. # lets try to read the URL that we've just built.
  462. request_string = urllib.urlopen(self._api_login_url, urllib.urlencode(argv))
  463. response = request_string.read()
  464. # do some basic error checking here so we can gracefully handle any errors we are likely to encounter
  465. if response.startswith(self._bad_request):
  466. raise PastebinError(response)
  467. return response
  468. def paste(self, api_dev_key, api_paste_code,
  469. api_user_key = None, paste_name = None, paste_format = None,
  470. paste_private = None, paste_expire_date = None):
  471. """Submit a code snippet to Pastebin using the new API.
  472. Usage Example::
  473. >>> from pastebin import PastebinAPI
  474. >>> x = PastebinAPI()
  475. >>> url = x.paste('453a994e0e2f1efae07f8759e59e075b' ,
  476. ... 'Snippet of code to paste goes here',
  477. ... paste_name = 'title of paste',
  478. ... api_user_key = 'c57a18e6c0ae228cd4bd16fe36da381a',
  479. ... paste_format = 'python',
  480. ... paste_private = 'unlisted',
  481. ... paste_expire_date = '10M')
  482. >>> print url
  483. http://pastebin.com/tawPUgqY
  484. @type api_dev_key: string
  485. @param api_dev_key: The API Developer Key of a registered U{http://pastebin.com} account.
  486. @type api_paste_code: string
  487. @param api_paste_code: The file or string to paste to body of the U{http://pastebin.com} paste.
  488. @type api_user_key: string
  489. @param api_user_key: The API User Key of a U{http://pastebin.com} registered user.
  490. If none specified, paste is made as a guest.
  491. @type paste_name: string
  492. @param paste_name: (Optional) Title of the paste.
  493. Default is to paste anonymously.
  494. @type paste_format: string
  495. @param paste_format: (Optional) Programming language of the code being
  496. pasted. This enables syntax highlighting when reading the code in
  497. U{http://pastebin.com}. Default is no syntax highlighting (text is
  498. just text and not source code).
  499. @type paste_private: string
  500. @param paste_private: (Optional) C{'public'} if the paste is public (visible
  501. by everyone), C{'unlisted'} if it's public but not searchable.
  502. C{'private'} if the paste is private and not searchable or indexed.
  503. The Pastebin FAQ (U{http://pastebin.com/faq}) claims
  504. private pastes are not indexed by search engines (aka Google).
  505. @type paste_expire_date: str
  506. @param paste_expire_date: (Optional) Expiration date for the paste.
  507. Once past this date the paste is deleted automatically. Valid
  508. values are found in the L{PastebinAPI.paste_expire_date} class member.
  509. If not provided, the paste never expires.
  510. @rtype: string
  511. @return: Returns the URL to the newly created paste.
  512. """
  513. # Valid api developer key
  514. argv = {'api_dev_key' : str(api_dev_key) }
  515. # Code snippet to submit
  516. if api_paste_code is not None:
  517. argv['api_paste_code'] = str(api_paste_code)
  518. # Valid API option - 'paste' is default for new paste
  519. argv['api_option'] = str('paste')
  520. # API User Key
  521. if api_user_key is not None:
  522. argv['api_user_key'] = str(api_user_key)
  523. elif api_user_key is None:
  524. argv['api_user_key'] = str('')
  525. # Name of the poster
  526. if paste_name is not None:
  527. argv['api_paste_name'] = str(paste_name)
  528. # Syntax highlighting
  529. if paste_format is not None:
  530. paste_format = str(paste_format).strip().lower()
  531. argv['api_paste_format'] = paste_format
  532. # Is the snippet private?
  533. if paste_private is not None:
  534. if paste_private == 'public':
  535. argv['api_paste_private'] = int(0)
  536. elif paste_private == 'unlisted':
  537. argv['api_paste_private'] = int(1)
  538. elif paste_private == 'private':
  539. argv['api_paste_private'] = int(2)
  540. # Expiration for the snippet
  541. if paste_expire_date is not None:
  542. paste_expire_date = str(paste_expire_date).strip().upper()
  543. argv['api_paste_expire_date'] = paste_expire_date
  544. # lets try to read the URL that we've just built.
  545. request_string = urllib.urlopen(self._api_url, urllib.urlencode(argv))
  546. response = request_string.read()
  547. # do some basic error checking here so we can gracefully handle any errors we are likely to encounter
  548. if response.startswith(self._bad_request):
  549. raise PastebinError(response)
  550. elif not response.startswith(self._prefix_url):
  551. raise PastebinError(response)
  552. return response
  553. def legacy_paste(self, paste_code,
  554. paste_name = None, paste_private = None,
  555. paste_expire_date = None, paste_format = None):
  556. """Unofficial python interface to the Pastebin legacy API.
  557. Unlike the official API, this one doesn't require an API key, so it's
  558. virtually anonymous.
  559. Usage Example::
  560. >>> from pastebin import PastebinAPI
  561. >>> x = PastebinAPI()
  562. >>> url = x.legacy_paste('Snippet of code to paste goes here',
  563. ... paste_name = 'title of paste',
  564. ... paste_private = 'unlisted',
  565. ... paste_expire_date = '10M',
  566. ... paste_format = 'python')
  567. >>> print url
  568. http://pastebin.com/tawPUgqY
  569. @type paste_code: string
  570. @param paste_code: The file or string to paste to body of the U{http://pastebin.com} paste.
  571. @type paste_name: string
  572. @param paste_name: (Optional) Title of the paste.
  573. Default is to paste with no title.
  574. @type paste_private: string
  575. @param paste_private: (Optional) C{'public'} if the paste is public (visible
  576. by everyone), C{'unlisted'} if it's public but not searchable.
  577. C{'private'} if the paste is private and not searchable or indexed.
  578. The Pastebin FAQ (U{http://pastebin.com/faq}) claims
  579. private pastes are not indexed by search engines (aka Google).
  580. @type paste_expire_date: string
  581. @param paste_expire_date: (Optional) Expiration date for the paste.
  582. Once past this date the paste is deleted automatically. Valid
  583. values are found in the L{PastebinAPI.paste_expire_date} class member.
  584. If not provided, the paste never expires.
  585. @type paste_format: string
  586. @param paste_format: (Optional) Programming language of the code being
  587. pasted. This enables syntax highlighting when reading the code in
  588. U{http://pastebin.com}. Default is no syntax highlighting (text is
  589. just text and not source code).
  590. @rtype: string
  591. @return: Returns the URL to the newly created paste.
  592. """
  593. # Code snippet to submit
  594. argv = { 'paste_code' : str(paste_code) }
  595. # Name of the poster
  596. if paste_name is not None:
  597. argv['paste_name'] = str(paste_name)
  598. # Is the snippet private?
  599. if paste_private is not None:
  600. argv['paste_private'] = int(bool(int(paste_private)))
  601. # Expiration for the snippet
  602. if paste_expire_date is not None:
  603. paste_expire_date = str(paste_expire_date).strip().upper()
  604. argv['paste_expire_date'] = paste_expire_date
  605. # Syntax highlighting
  606. if paste_format is not None:
  607. paste_format = str(paste_format).strip().lower()
  608. argv['paste_format'] = paste_format
  609. # lets try to read the URL that we've just built.
  610. request_string = urllib.urlopen(self._legacy_api_url, urllib.urlencode(argv))
  611. response = request_string.read()
  612. # do some basic error checking here so we can gracefully handle any errors we are likely to encounter
  613. if response.startswith(self._bad_request):
  614. raise PastebinError(response)
  615. elif not response.startswith(self._prefix_url):
  616. raise PastebinError(response)
  617. return response
  618. ######################################################
  619. delete_paste = PastebinAPI.delete_paste
  620. user_details = PastebinAPI.user_details
  621. trending = PastebinAPI.trending
  622. pastes_by_user = PastebinAPI.pastes_by_user
  623. generate_user_key = PastebinAPI.generate_user_key
  624. legacy_paste = PastebinAPI.legacy_paste
  625. paste = PastebinAPI.paste
  626. ######################################################
  627. if __name__ == "__main__":
  628. main()