Simple Web commands

Just some ideas/code written down, so i don’t forget how to do them again….

September 26, 2008 at 7:17 pm Leave a comment

How to manually activate Plones version history

If you wish to use Plones version history within a script, then you can use the function applyVersionControl within the portal_workflow tool.

If you activate this first, then set the changes of the object, then it will automatically update the version history for the given object.

The example below shows the retraction of a Document object to the private state.  Then it updates the version history before setting the body text of the document.  A reindex, of the object, is required for the ZODB to be updated.

class activateVersionHistory(BrowserView):
    def __call__(self):
        portal_catalog  = getToolByName(self.context, 'portal_catalog')
        portal_workflow = getToolByName(self.context, 'portal_workflow')
        doc      = portal_catalog(portal_type='Document')
        if doc:
            thisPage = doc[0]
            obj      = thisPage.getObject()
            state    = portal_workflow.doActionFor(obj ,'retract')
            portal_repository = getToolByName(self.context, "portal_repository")
            portal_repository.applyVersionControl(obj, comment='Manually activated workflow')
            obj.setText('Example body text - Manually set')
            obj.reindexObject()

February 5, 2012 at 9:16 pm Leave a comment

Using the Twitter api – Via a Plone portlet

Recently I was asked to use the Twitter api to grab given feeds into the a Plone site portlet.  I haven’t used Twitter myself as I often use other social network sites, but I have to say I found the api very useful and straight forward.   You can find it at http://apiwiki.twitter.com/

Unfortunately when I first wrote the script the api was offline for a few hours.  When I have a second more I’ll create a regular expresion to sort out the urls in the tweets, but this will do for now.

You will need to declare the portlet in the portlet.xml file and within the browser configuire.zcml, as this is where this script sits.

from zope.interface import implements
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.memoize.compress import xhtml_compress
from zope.formlib import form
from Products.Five.browser.
pagetemplatefile import ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName
import urllib
import datetime

import simplejson
from plone.app.portlets.portlets import base

from plone.portlets.interfaces import IPortletDataProvider
from zope.component import queryAdapter

from zope import schema

class ITwitterPortlet (IPortletDataProvider):

    Twitter = schema.TextLine(
        title=u"Twitter Id",
        description=u"Enter in the twitter Id without the #, For
 example: BBCNews",
        required=True)

class Assignment(base.Assignment):
    implements(ITwitterPortlet)

    header = u"Twitter feed links"
    Twitter = u""

    def __init__(self,
                 Twitter=None,
                 ):
        self.Twitter = Twitter

    @property
    def title(self):
        """Title given on manage portlets screen
        """
        return u"Twitter Feeds"

class Renderer(base.Renderer):

 """ Where the output will be finally seen """
    _template = ViewPageTemplateFile('twitter_portlet.pt')

    def __init__(self, *args):
        base.Renderer.__init__(self, *args)

    @memoize
    def getTweets(self):
        tweetid = self.data.Twitter
        if tweetid:
            readurl = self.readTwitter(tweetid)
            if readurl:
                tweet   = simplejson.loads(readurl)
                if tweet:
                    tw_text     = tweet[0]['text']
                    tw_user_img = tweet[0]['user']['profile_image_url']
                    tw_created  = tweet[0]['created_at']
                    tw_user     = tweet[0]['user']['screen_name']
                    if 'http://' in tw_text:
                        tw_t    = tw_text.split(' ')
                        format_tw = []
                        for x in tw_t:
                            if 'http://' in x:
 #This is the bit where a regular expression would be handy
                                x_ammend = x.replace('http://','<a href="http://')
                                format_tw.append(x_ammend+'">'+x+'</a>')
                            else:
                                format_tw.append(x)
                            tw_text = ' '.join(format_tw)
                     return {'text'            : tw_text,
                             'twitter_user_img': tw_user_img,
                             'twitter_created' : tw_created,
                             'twitter_user'    : tw_user})
                    else:
                        pass
            else:
             return None

    def readTwitter(self, twitterU):
        twitter_url =
 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=%s&count=1'%str(twitterU)
        try:
            url     = urllib.urlopen(twitter_url)
            readurl = url.read()
            url.close()
        return readurl
        except URLError, e:
 print e.reason
 return None

    def render(self):
        return self._template()

 class AddForm(base.AddForm):
    form_fields = form.Fields(ITwitterPortlet)
    label = u"Add Twitter feeds to the site"
    description = u"A portlet which can display a given Twitter feed"

    def create(self, data):
        return Assignment(**data)

 class EditForm(base.EditForm):
    form_fields = form.Fields(ITwitterPortlet)
    label = u"Edit a Twitter portlet"
    description = u"A portlet which can display a given Twitter feed"

May 31, 2011 at 7:45 pm Leave a comment

Updating plone content via a browser view

After creating your content type, you can update existing content pretty easily by using a browser view.  You can read more about this on http://plone.org/documentation/kb/creating-a-minimalistic-zope-3-view

You can update any of the content from this content type by placing set infront of the title.  For example;

brains = context.portal_catalog(portal_type="Event")
for event in brains:
    event_object = event.getObject()
    event_object.setTitle('Title')

This sample code will obviously set all events to have the title “Title” which isn’t very handy, but you can see how its used. Its good if you want to update migrated objects with new schema items.

October 31, 2010 at 3:15 am Leave a comment

Image resizer using python

Here is a quick python script to resize images.  I use this to resize my images for facebook, as i currently have a very bad internet connection, they have to be small.

from PIL import Image
import glob, os

#defaults to landscape
size = 667, 1000

for infile in glob.glob("*.JPG"):
    file, ext = os.path.splitext(infile)
    im = Image.open(infile)
    if im.size[0] > im.size[1]:
        #if its a portrait
        size = 1000, 667
    im.thumbnail(size, Image.ANTIALIAS)
    im.save("FB-"+file+'.jpg', "JPEG")

October 31, 2010 at 2:59 am Leave a comment

overwriting plone product widgets

If you want to overwrite plone edit inputs, for example if you want the id of a page to be set on the fly instead of by the user input, then you could use a mixture of input fields and javascript.

For example if you had a profile section of the site, you could have the id of the page to be the profiles name.

to do this have the following JS, Jquery is also required;

<script language="javascript">
function insertid(name){
var value = name;
var name1 = document.getElementById('name1');
name1 = name1.value;
title1 = title1.value;
name1 = name1.toLowerCase();
name = name.toLowerCase();
rtnvar = name1+'-'+name;
$("#retn").attr('value',rtnvar);
}
</script>

Then the HTML code can look something like this

<p><b>First name</b><br />
<input type="text" name="first_name" id="name1" tal:attributes="value here/first_name" /> * Required field</p>
<p><b>Surname</b><br /> 
<input type="text" name="last_name" tal:attributes="value here/last_name" onchange="insertid(this.value)" /> * Required field</p>
<input type="hidden" id="retn" name="id" tal:attributes="value python: here.name.lower()+'-'+here.name1.lower()" />

The js creates an output via jquery to a hidden input that writes the ID

Then the tal:attributes in the hidden input make sure that if the user reuses the edit page, their details wont be lost.

When the page is saved the url should be;

 http://localhost/$name-$name1

When $name and $name1 are the input variables.

October 15, 2009 at 3:07 pm Leave a comment

avoiding errors when using Tal

You can use the;

tal:on-error="nothing"

to avoid errors on the page.  This is useful if you don’t care about fixing all errors on a page as if an error exists this wont inform you of an error. Good for demos, but errors should obviously be fixed.

October 15, 2009 at 2:55 pm Leave a comment

avoid using restricted python in Plone 2.5 with external methods

You can create scripts within the /extension folders that are fully functional, i.e. XML readers or system command files. Then you can refer to them from within the ZMI via an external method. There are pretty quick and easy way of transfering content from other servers into Plone and can be extremely useful. Trouble is they often cache, which is normally a good thing, unless you have an error in your script.

October 12, 2009 at 10:08 pm Leave a comment

including html content on a page via javascript

I have stopped using this, as now i use jquerys .html() or .text() now, but i thought i’d remind myself.

write;

<script language="JavaScript" src="link to URL" type="text/javascript"></script>

and then the script should look something like;

document.write('content here or database query')

You might have to play around with the outputted content so that you create a valid script output.

October 6, 2009 at 10:41 am Leave a comment

jquery/ajax calling a python script

its pretty easy to call a script now with Jquery, i really like it;

<script type="text/javascript" src="/jquery.js"></script>
<script>
   function getcontent(inp){
    $("#retn").empty()
    $.ajax({
       type: "GET",
       url: "getinfo.py?year="+inp,
       dataType: "script",
       success: function(html){
         $("#retn").append(html);
       }

    });
};
</script>

Calling the script:

<select onchange="getcontent(this.options[this.selectedIndex].value)">
<option></option>
</select>

August 21, 2009 at 11:11 am 2 comments

Jquery cycle example

I have recently developed a cycle add-on which includes; the cycle effect, next previous buttons and some sort of text effect over the images. This is developed from http://www.malsup.com/jquery/cycle/

The full demo of this can be seen at http://adamcastle.co.uk/jqueryexample.html

The main bulk of the code is below;

$(function() {

$(‘#slideshow’).cycle({
fx:      ‘scrollHorz’,
timeout:  0,
prev:    ‘#prev’,
next:    ‘#next’,
pager:   ‘#nav’,
pagerAnchorBuilder: pagerFactory
});

function pagerFactory(idx, slide) {
var s = idx > 2 ? ‘ style=”display:none”‘ : ”;
return ‘<li’+s+’><a href=”#”>’+(idx+1)+'</a></li>’;
};

});

July 20, 2009 at 8:11 am Leave a comment

Older Posts


May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031