Блогът на Фил

Nothing to see here, move along
  • rss
  • Home
  • About
  • profiles

Понякога PERL ме кефи повече от Python

felipe

Идеята да мога програмно да публикувам в блога си ми хрумна когато въвеждам книги и филми в една програма каталог – gcstar. Та идеята е като въведа нова книга или нов филм вътре gcstar автоматично да публикува предефинирано съобщение за това че съм купил съответното нещо, или ако въведа коментар – да го публикува. Така ще ми спести доста време.
И понеже gcstar е писана на PERL, реших да проверя как стои въпросът с публикуване в livejournal чрез PERL.
Отидох на онлайн хранилището за pERL модули, наречено CPAN и намерих модула LJ-Simple-0.15. Чрез него програма, която публикува във вашия блог изглежда така:

use LJ::Simple;

LJ::Simple::QuickPost(
user => “test”,
pass => “test”,
entry => “Just a simple entry”,
) || die “$0: Failed to post entry: $LJ::Simple::error\n”;

Уникално, а?
Най-много ми харесва скоростта, с която се решават проблеми чрез CPAN. Трябва ти някаква функционалност, търсиш в CPAN, намираш нужния ти модул, инсталираш го, копираш примера от задължителната документация и имаш работещо решение. Гениално!

Comments
No Comments »
Categories
Uncategorized
Comments rss Comments rss
Trackback Trackback

431

felipe

Just a simple entry

Comments
No Comments »
Categories
Uncategorized
Comments rss Comments rss
Trackback Trackback

’110497′

felipe

Just a simple entry

Comments
No Comments »
Categories
Uncategorized
Comments rss Comments rss
Trackback Trackback

python livejournal

felipe

Днес реших да потърся начин да публикувам в блога си програмно чрез Python. След тестване на различни кодове успях да модифицирам този – http://hewgill.com/ljdump/ и се получи следното приложенийце, с което публикувах предишния запис:

#!/usr/bin/python

#
# ljdump.py – livejournal archiver
# Greg Hewgill <greg@hewgill.com> http://hewgill.com
# Version 1.2
#
# $Id: ljdump.py 17 2006-09-08 08:46:56Z greg $
#
# This program reads the journal entries from a livejournal (or compatible)
# blog site and archives them in a subdirectory named after the journal name.
#
# The configuration is read from “ljdump.config”. A sample configuration is
# provided in “ljdump.config.sample”, which should be copied and then edited.
# The configuration settings are:
#
#   server – The XMLRPC server URL. This should only need to be changed
#            if you are dumping a journal that is livejournal-compatible
#            but is not livejournal itself.
#
#   username – The livejournal user name. A subdirectory will be created
#              with this same name to store the journal entries.
#
#   password – The account password. This password is never sent in the
#              clear; the livejournal “challenge” password mechanism is used.
#
# This program may be run as often as needed to bring the backup copy up
# to date. Both new and updated items are downloaded.
#
# LICENSE
#
# This software is provided 'as-is', without any express or implied
# warranty.  In no event will the author be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
#    claim that you wrote the original software. If you use this software
#    in a product, an acknowledgment in the product documentation would be
#    appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
#    misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
#
# Copyright (c) 2005-2006 Greg Hewgill

import codecs, md5, os, pickle, pprint, re, sys, urllib2, xml.dom.minidom, xmlrpclib
from xml.sax import saxutils

def calcchallenge(challenge, password):
    return md5.new(challenge+md5.new(password).hexdigest()).hexdigest()

def flatresponse(response):
    r = {}
    while True:
        name = response.readline()
        if len(name) == 0:
            break
        if name[-1] == '\n':
            name = name[:len(name)-1]
        value = response.readline()
        if value[-1] == '\n':
            value = value[:len(value)-1]
        r[name] = value
    return r

def getljsession(username, password):
    r = urllib2.urlopen(Server+”/interface/flat”, “mode=getchallenge”)
    response = flatresponse(r)
    r.close()
    r = urllib2.urlopen(Server+”/interface/flat”, “mode=sessiongenerate&user=%s&auth_method=challenge&auth_challenge=%s&auth_response=%s” % (username, response['challenge'], calcchallenge(response['challenge'], password)))
    response = flatresponse(r)
    r.close()
    return response['ljsession']

def dochallenge(params, password):
    challenge = server.LJ.XMLRPC.getchallenge()
    params.update({
        'auth_method': “challenge”,
        'auth_challenge': challenge['challenge'],
        'auth_response': calcchallenge(challenge['challenge'], password)
    })
    return params

config = xml.dom.minidom.parse(“ljdump.config”)
Server = config.documentElement.getElementsByTagName(“server”)[0].childNodes[0].data
Username = config.documentElement.getElementsByTagName(“username”)[0].childNodes[0].data
Password = config.documentElement.getElementsByTagName(“password”)[0].childNodes[0].data

m = re.search(“(.*)/interface/xmlrpc”, Server)
if m:
    Server = m.group(1)

print “Fetching journal entries for: %s” % Username
try:
    os.mkdir(Username)
    print “Created subdirectory: %s” % Username
except:
    pass

ljsession = getljsession(Username, Password)

server = xmlrpclib.ServerProxy(Server+”/interface/xmlrpc”)

newentries = 0
newcomments = 0
errors = 0

lastsync = “”
lastmaxid = 0
try:
    f = open(“%s/.last” % Username, “r”)
    lastsync = f.readline()
    if lastsync[-1] == '\n':
        lastsync = lastsync[:len(lastsync)-1]
    lastmaxid = f.readline()
    if len(lastmaxid) > 0 and lastmaxid[-1] == '\n':
        lastmaxid = lastmaxid[:len(lastmaxid)-1]
    if lastmaxid == “”:
        lastmaxid = 0
    else:
        lastmaxid = int(lastmaxid)
    f.close()
except:
    pass
origlastsync = lastsync

r = server.LJ.XMLRPC.login(dochallenge({
    'username': Username,
    'ver': 1,
    'getpickws': 1,
    'getpickwurls': 1,
}, Password))
userpics = dict(zip(r['pickws'], r['pickwurls']))
userpics['*'] = r['defaultpicurl']

r = server.LJ.XMLRPC.syncitems(dochallenge({
        'username': Username,
        'ver': 1,
        'lastsync': lastsync,
    }, Password))
    #pprint.pprint(r)
e = server.LJ.XMLRPC.postevent(dochallenge({
                    'username': Username,
                    'ver': 1,
                    'selecttype': “one”,
                    'event': 'please work',
                    'subject':'test',
                    'year':'2008',
                    'mon':'8',
                    'day':'26',
                    'hour':'12',
                    'min':'8' 
                }, Password))

Comments
No Comments »
Categories
Uncategorized
Comments rss Comments rss
Trackback Trackback

test

felipe

please work

Comments
No Comments »
Categories
Uncategorized
Comments rss Comments rss
Trackback Trackback

A Supernova Cocoon Breakthrough

 
Observations with NASA's Chandra X-ray Observatory have provided the first X-ray evidence of a supernova shock wave breaking through a cocoon of gas surrounding the star that exploded. This discovery may help astronomers understand why some supernovas are much more powerful than others. On Nov. 3, 2010, a supernova was discovered in the galaxy UGC 5189A, located about 160 million light years away. Using data from the All Sky Automated Survey telescope in Hawaii taken earlier, astronomers determined this supernova exploded in early October 2010 (in Earth's time-frame). This composite image of UGC 5189A shows X-ray data from Chandra in purple and optical data from Hubble Space Telescope in red, green and blue. SN 2010jl is the very bright X-ray source near the top of the galaxy. A team of researchers used Chandra to observe this supernova in December 2010 and again in October 2011. The supernova was one of the most luminous that has ever been detected in X-rays. The results of these observations were published in a paper that appeared in the May 1, 2012 issue of The Astrophysical Journal Letters. Credits: X-ray: NASA/CXC/Royal Military College of Canada/P.Chandra et al); Optical: NASA/STScI
Read More

Случаен цитат

Hope, it is the quintessential human delusion, simultaneously the source of your greatest strength, and your greatest weakness. — The Architect

I am reading now

Cryptonomicon
635 / Pages
Cryptonomicon

 

August 2008
M T W T F S S
« Jul   Sep »
 123
45678910
11121314151617
18192021222324
25262728293031

чурулик

  • more shaking
  • f#@!%ing scary earthquake in Sofia at 3:00 - 5.8 magnitude
  • http://t.co/ln0q8N8Z but fracking is completely safe, trust us!

Blogroll

  • Блогът на Дино
  • Блогът на Камен
  • Блогът на Краси
  • Търсене в интернет

User-submitted Links

No recommended links yet. Add one?

  • Newest
  • Hot
  • Current
  • Top ranked

Spam

7,784
SPAM BLOCKED
rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox