Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Cache Parse() results #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 15, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
PWD = $(shell pwd)

all: prep test
all: prep test

prep:
#git submodule update --init
#sudo apt-get install python-yaml

test:
@#test ! -d tmp && mkdir tmp
@export PYTHONPATH=tmp && python setup.py develop -d tmp
Expand All @@ -21,4 +19,4 @@ clean:
@rm -rf tmp\
ua_parser.egg-info

.PHONY: all clean
.PHONY: all prep test clean
14 changes: 13 additions & 1 deletion ua_parser/user_agent_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,10 @@ def Parse(self, user_agent_string):
return device, brand, model


MAX_CACHE_SIZE = 20
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the same size as what urlparse uses. I don't have a strong opinion about more or less. This can be changed, obviously, at runtime with user_agent_parser.MAX_CACHE_SIZE = 100 or something.

>>> import urlparse
>>> urlparse.MAX_CACHE_SIZE
20

_parse_cache = {}


def Parse(user_agent_string, **jsParseBits):
""" Parse all the things
Args:
Expand All @@ -205,12 +209,20 @@ def Parse(user_agent_string, **jsParseBits):
A dictionary containing all parsed bits
"""
jsParseBits = jsParseBits or {}
return {
key = (user_agent_string, repr(jsParseBits))
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not happy with using repr() like this, but we need a hashable type to use as a key.

cached = _parse_cache.get(key)
if cached is not None:
return cached
if len(_parse_cache) > MAX_CACHE_SIZE:
_parse_cache.clear()
v = {
'user_agent': ParseUserAgent(user_agent_string, **jsParseBits),
'os': ParseOS(user_agent_string, **jsParseBits),
'device': ParseDevice(user_agent_string, **jsParseBits),
'string': user_agent_string
}
_parse_cache[key] = v
return v


def ParseUserAgent(user_agent_string, **jsParseBits):
Expand Down