Is there any way to make this function look nicer?
Question: I need a logic that will extract a url from Apache log file: right now I did
this:

    
    
    apache_log = {'@source': 'file://xxxxxxxxxxxxxxx//var/log/apache2/access.log', '@source_host': 'xxxxxxxxxxxxxxxxxxx', '@message': 'xxxxxxxxxxxxxxx xxxxxxxxxx - - [02/Aug/2013:12:38:37 +0000] "POST /user/12345/product/2 HTTP/1.1" 404 513 "-" "PycURL/7.26.0"', '@tags': [], '@fields': {}, '@timestamp': '2013-08-02T12:38:38.181000Z', '@source_path': '//var/log/apache2/access.log', '@type': 'Apache-access'}
    data = apache_log['@message'].split()
    if data.index('"POST') and data[data.index('"POST')+2].startswith('HTTP'):
         print data[data.index('"POST')+1] 
    

It returns me:

    
    
    /user/12345/product/2
    

Basically the result is correct, but the way I did it I don't really like.

Can someone suggest better (more Pythonic) way of extracting this path from
apache log file.


Answer: A regular expression would work better:

    
    
    import re
    
    post_path = re.compile(r'"POST (/\S+) HTTP')
    
    match = post_path.search(apache_log['@message'])
    if match:
        print match.group(1)
    

Demo:

    
    
    >>> import re
    >>> apache_log = {'@source': 'file://xxxxxxxxxxxxxxx//var/log/apache2/access.log', '@source_host': 'xxxxxxxxxxxxxxxxxxx', '@message': 'xxxxxxxxxxxxxxx xxxxxxxxxx - - [02/Aug/2013:12:38:37 +0000] "POST /user/12345/product/2 HTTP/1.1" 404 513 "-" "PycURL/7.26.0"', '@tags': [], '@fields': {}, '@timestamp': '2013-08-02T12:38:38.181000Z', '@source_path': '//var/log/apache2/access.log', '@type': 'Apache-access'}
    >>> post_path = re.compile(r'"POST (/\S+) HTTP')
    >>> match = post_path.search(apache_log['@message'])
    >>> if match:
    ...     print match.group(1)
    ... 
    /user/12345/product/2
    

