This document discusses Python and web frameworks. It begins with an introduction to Python and its advantages for web development. It then discusses several popular Python web frameworks including web.py, Flask, and Django. It also covers related topics like WSGI, templating with Jinja2, asynchronous programming, and deployment with virtualenv.
The goal of this presentation is to broaden your knowledge of Python, exploring some concepts and techniques you might have never heard about. I won't go into too much detail, the goal is only to inspire you to research those features and patterns.
Euro python2011 High Performance PythonIan Ozsvald
I ran this as a 4 hour tutorial at EuroPython 2011 to teach High Performance Python coding.
Techniques covered include bottleneck analysis by profiling, bytecode analysis, converting to C using Cython and ShedSkin, use of the numerical numpy library and numexpr, multi-core and multi-machine parallelisation and using CUDA GPUs.
Write-up with 49 page PDF report: http://ianozsvald.com/2011/06/29/high-performance-python-tutorial-v0-1-from-my-4-hour-tutorial-at-europython-2011/
The goal of this presentation is to broaden your knowledge of Python, exploring some concepts and techniques you might have never heard about. I won't go into too much detail, the goal is only to inspire you to research those features and patterns.
Euro python2011 High Performance PythonIan Ozsvald
I ran this as a 4 hour tutorial at EuroPython 2011 to teach High Performance Python coding.
Techniques covered include bottleneck analysis by profiling, bytecode analysis, converting to C using Cython and ShedSkin, use of the numerical numpy library and numexpr, multi-core and multi-machine parallelisation and using CUDA GPUs.
Write-up with 49 page PDF report: http://ianozsvald.com/2011/06/29/high-performance-python-tutorial-v0-1-from-my-4-hour-tutorial-at-europython-2011/
The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 2:
- Slots vs Dictionaries
- Basic and Advanced Generators
- Async programming
This presentation covers Python most important data structures like Lists, Dictionaries, Sets and Tuples. Exception Handling and Random number generation using simple python module "random" also covered. Added simple python programs at the end of the presentation
Odessapy2013 - Graph databases and PythonMax Klymyshyn
Page 10 "Я из Одессы я просто бухаю." translation: I'm from Odessa I just drink. Meaning his drinking a lot of "Vodka" ^_^ (@tuc @hackernews)
This is local meme - when someone asking question and you will look stupid in case you don't have answer.
Installing and Using Python
Basic I/O
Variables and Expressions
Conditional Code
Functions
Loops and Iteration
Python Data Structures
Errors and Exceptions
Object Oriented with Python
Multithreaded Programming with Python
Install/Create and Using Python Library
Compile Python Script
Resources
===========================
and 7 Quizzes
This presentation was given online in July 2017 and will be given at the NY Java SIG later this year. It progressively builds on Java 8 concepts using puzzles and coding to give students confidence in their Java 8 stream/lambda skills. Handouts and code in https://github.com/boyarsky/java-8-streams-by-puzzles
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5PyNSK
Автор доклада: Александр Сапронов.
Обзорный мини-доклад. В докладе вы найдете причину релиза 2.7.11 и новинки Python 3.5
Доклад сделан на 2 встрече сообщества PyNSK
Python 101++: Let's Get Down to Business!Paige Bailey
You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
This presentation contains a quick tour in Python world. First by By comparing Java code, and the equivalent Python side by side, Second by listing some cool features in Python, finally by listing downs and ups of Python in usage; when to use python and when not.
The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 2:
- Slots vs Dictionaries
- Basic and Advanced Generators
- Async programming
This presentation covers Python most important data structures like Lists, Dictionaries, Sets and Tuples. Exception Handling and Random number generation using simple python module "random" also covered. Added simple python programs at the end of the presentation
Odessapy2013 - Graph databases and PythonMax Klymyshyn
Page 10 "Я из Одессы я просто бухаю." translation: I'm from Odessa I just drink. Meaning his drinking a lot of "Vodka" ^_^ (@tuc @hackernews)
This is local meme - when someone asking question and you will look stupid in case you don't have answer.
Installing and Using Python
Basic I/O
Variables and Expressions
Conditional Code
Functions
Loops and Iteration
Python Data Structures
Errors and Exceptions
Object Oriented with Python
Multithreaded Programming with Python
Install/Create and Using Python Library
Compile Python Script
Resources
===========================
and 7 Quizzes
This presentation was given online in July 2017 and will be given at the NY Java SIG later this year. It progressively builds on Java 8 concepts using puzzles and coding to give students confidence in their Java 8 stream/lambda skills. Handouts and code in https://github.com/boyarsky/java-8-streams-by-puzzles
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5PyNSK
Автор доклада: Александр Сапронов.
Обзорный мини-доклад. В докладе вы найдете причину релиза 2.7.11 и новинки Python 3.5
Доклад сделан на 2 встрече сообщества PyNSK
Python 101++: Let's Get Down to Business!Paige Bailey
You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
This presentation contains a quick tour in Python world. First by By comparing Java code, and the equivalent Python side by side, Second by listing some cool features in Python, finally by listing downs and ups of Python in usage; when to use python and when not.
The Agenda for the Webinar:
1. Introduction to Python.
2. Python and Big Data.
3. Python and Data Science.
4. Key features of Python and their usage in Business Analytics.
5. Business Analytics with Python – Real world Use Cases.
Big Data & NoSQL - EFS'11 (Pavlo Baron)Pavlo Baron
That's the slides of my half day workshop at the EFS'11 in Stuttgart where I covered some theoretical aspects of NoSQL data stores relevant for dealing with large data amounts
Python's "batteries included" philosophy means that it comes with an astonishing amount of great stuff. On top of that, there's a vibrant world of third-party libraries that help make Python even more wonderful. We'll go on a breezy, example-filled tour through some of my favorites, from treasures in the standard library to great third-party packages that I don't think I could live without, and we'll touch on some of the fuzzier aspects of the Python culture that make it such a joy to be part of.
Python and Oracle : allies for best of data managementLaurent Leturgez
In this presentation, I described Python and how Python can Interact with Oracle database, and Oracle Cloud Infrastructure in various project : from data visualisation to data science.
A Recovering Java Developer Learns to GoMatt Stine
As presented at OSCON 2014.
The Go programming language has emerged as a favorite tool of DevOps and cloud practitioners alike. In many ways, Go is more famous for what it doesn’t include than what it does, and co-author Rob Pike has said that Go represents a “less is more” approach to language design.
The Cloud Foundry engineering teams have steadily increased their use of Go for building components, starting with the Router, and progressing through Loggregator, the CLI, and more recently the Health Manager. As a “recovering-Java-developer-turned-DevOps-junkie” focused on helping our customers and community succeed with Cloud Foundry, it became very clear to me that I needed to add Go to my knowledge portfolio.
This talk will introduce Go and its distinctives to Java developers looking to add Go to their toolkits. We’ll cover Go vs. Java in terms of:
* type systems
* modularity
* programming idioms
* object-oriented constructs
* concurrency
Six Feet Up's senior developer Clayton Parker will lead you on a journey to become a Python zen master. Your code should be as fashionable as it is functional. To quote the Zen of Python, "Beautiful is better than ugly". This talk will teach you about the Python style guide and why it is important. The talk will show you examples of well written Python and how to analyze your current code to make Guido proud.
Using functional concepts in Python. Introduction to functional programming and exploring each of the concepts, like map, filter and reduce in detail and how functional programming can help creating massively parallel software systems
In this presentation Combinatorial Optimization: The Knapsack Problem and Solution, solved by our programming homework help expert. This is a sample of what our experts can do. If you need any python homework help. Then you can email us at support@programminghomeworkhelp.com
Python 101 language features and functional programmingLukasz Dynowski
Presentation reviles the syntax solution for common encountered programming challenges, gives insight in to python datatypes, and explains core design principles behind the program
Similar to Python于Web 2.0网站的应用 - QCon Beijing 2010 (20)
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Elevating Tactical DDD Patterns Through Object Calisthenics
Python于Web 2.0网站的应用 - QCon Beijing 2010
1. Python
Web 2.0
QCon Beijing 2010
http://www.flickr.com/photos/arnolouise/2986467632/
2. About Me
• Python
• 2002 Python
• 2004
Python
• http://www.douban.com/
people/hongqn/
• hongqn@douban.com
• http://twitter.com/hongqn
3. Python
• Python is a programming language that lets you
work more quickly and integrate your systems more
effectively. You can learn to use Python and see
almost immediate gains in productivity and lower
maintenance costs. (via http://python.org/)
4. Languages in
C
27%
Javascript
12%
C++
Python 3%
58%
(Pyrex/R/Erlang/Go/Shell)
1%
13. : 13
import os
from collections import defaultdict
d = defaultdict(int)
for dirpath, dirnames, filenames in os.walk('.'):
for filename in filenames:
path = os.path.join(dirpath, filename)
ext = os.path.splitext(filename)[1]
d[ext] += len(list(open(path)))
for ext, n_lines in d.items():
print ext, n_lines
28. Why so many Python
web frameworks?
• Because you can write your own
framework in 3 hours and a total of 60
lines of Python code.
• http://bitworking.org/news/
Why_so_many_Python_web_frameworks
29. doctest
def cube(x):
"""
>>> cube(10)
1000
"""
return x * x
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
30. nose http://somethingaboutorange.com/mrl/projects/nose/
from cube import cube
def test_cube():
result = cube(10)
assert result == 1000
31. numpy http://numpy.scipy.org/
>>> from numpy import *
>>> A = arange(4).reshape(2, 2)
>>> A
array([[0, 1],
[2, 3]])
>>> dot(A, A.T)
array([[ 1, 3],
[ 3, 13]])
32. ipython http://numpy.scipy.org/
$ ipython -pylab
In [1]: X = frange(0, 10, 0.1)
In [2]: Y = [sin(x) for x in X]
In [3]: plot(X, Y)
33. ipython http://numpy.scipy.org/
$ ipython -pylab
In [1]: X = frange(0, 10, 0.1)
In [2]: Y = [sin(x) for x in X]
In [3]: plot(X, Y)
37. >>> import this
The Zen of Python, by Tim Peters http://bit.ly/pyzencn
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to
break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
38. In the face of ambiguity, refuse the
temptation to guess.
There should be one-- and
preferably only one --obvious way
to do it.
Although that way may not be Python
obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than
*right* now.
If the implementation is hard to
explain, it's a bad idea.
If the implementation is easy to
explain, it may be a good idea.
Namespaces are one honking great
idea -- let's do more of those!
39. Simple is better than
complex
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World!");
}
}
44. Readability counts
• {} end
• (except "@" for
decorators)
if limit is not None and len(ids)>limit:
ids = random.sample(ids, limit)
45. TOOWTDI
• There (should be) Only One Way To Do It.
• vs. Perlish TIMTOWTDI (There Is More
Than One Way To Do It)
46. TOOWTDI
• There (should be) Only One Way To Do It.
• vs. Perlish TIMTOWTDI (There Is More
Than One Way To Do It)
a = [1, 2, 3, 4, 5]
b = []
for i in range(len(a)):
b.append(a[i]*2)
47. TOOWTDI
• There (should be) Only One Way To Do It.
• vs. Perlish TIMTOWTDI (There Is More
Than One Way To Do It)
a = [1, 2, 3, 4, 5]
b = []
for i in range(len(a)):
b.append(a[i]*2)
48. TOOWTDI
• There (should be) Only One Way To Do It.
• vs. Perlish TIMTOWTDI (There Is More
Than One Way To Do It)
a = [1, 2, 3, 4, 5] b = []
b = [] for x in a:
for i in range(len(a)):
b.append(x*2)
b.append(a[i]*2)
49. TOOWTDI
• There (should be) Only One Way To Do It.
• vs. Perlish TIMTOWTDI (There Is More
Than One Way To Do It)
a = [1, 2, 3, 4, 5] b = []
b = [] for x in a:
for i in range(len(a)):
b.append(x*2)
b.append(a[i]*2)
50. TOOWTDI
• There (should be) Only One Way To Do It.
• vs. Perlish TIMTOWTDI (There Is More
Than One Way To Do It)
b = [x*2 for x in a]
90. def cache(key):
def deco(func):
def _(*args, **kwargs):
r = mc.get(key)
if r is None:
r = func(*args, **kwargs)
mc.set(key, r)
return r
return _
return deco
91. def cache(key):
def deco(func):
def _(*args, **kwargs):
r = mc.get(key)
if r is None:
r = func(*args, **kwargs)
mc.set(key, r)
return r
return _
return deco
92. cache key
def get_review(id):
key = 'review:%s' % id
review = mc.get(key)
if review is None: # cache miss
id, author_id, text = exc_sql("select id, author_id,
text from review where id=%s", id)
review = Review(id, author_id, text)
mc.set(key, review)
return review
93. cache key
decorator
@cache('review:{id}')
def get_review(id):
id, author_id, text = exc_sql("select id, author_id,
text from review where id=%s", id)
return Review(id, author_id, text)
94. def cache(key_pattern, expire=0):
def deco(f):
arg_names, varargs, varkw, defaults = inspect.getargspec(f)
if varargs or varkw:
raise Exception("not support varargs")
gen_key = gen_key_factory(key_pattern, arg_names, defaults)
def _(*a, **kw):
key = gen_key(*a, **kw)
r = mc.get(key)
if r is None:
r = f(*a, **kw)
mc.set(key, r, expire)
return r
return _
return deco
95. def cache(key_pattern, expire=0):
def deco(f):
arg_names, varargs, varkw, defaults = inspect.getargspec(f)
if varargs or varkw:
raise Exception("not support varargs")
gen_key = gen_key_factory(key_pattern, arg_names, defaults)
def _(*a, **kw):
key = gen_key(*a, **kw)
r = mc.get(key)
if r is None:
r = f(*a, **kw)
mc.set(key, r, expire)
return r
return _
return deco
96. def cache(key_pattern, expire=0):
def deco(f):
arg_names, varargs, varkw, defaults = inspect.getargspec(f)
if varargs or varkw:
raise Exception("not support varargs")
gen_key = gen_key_factory(key_pattern, arg_names, defaults)
def _(*a, **kw):
key = gen_key(*a, **kw)
r = mc.get(key)
if r is None:
r = f(*a, **kw)
mc.set(key, r, expire)
return r
return _
return deco
103. class Feed(object):
def get_entries(self, limit=10):
ids = exc_sqls("select id from entry where feed_id=
%s order by id desc limit %s", (self.id, limit))
return [Entry.get(id) for id in ids]
class FeedCollection(object):
def get_entries(self, limit=10):
mixed_entries = []
for feed in self.feeds:
entries = feed.get_entries(limit=limit)
mixed_entries += entries
mixed_entries.sort(key=lambda e: e.id, reverse=True)
return mixed_entries[:10]
104. class Feed(object):
def get_entries(self, limit=10):
ids = exc_sqls("select id from entry where feed_id=
%s order by id desc limit %s", (self.id, limit))
return [Entry.get(id) for id in ids]
class FeedCollection(object):
def get_entries(self, limit=10):
mixed_entries = []
for feed in self.feeds:
entries = feed.get_entries(limit=limit)
mixed_entries += entries
mixed_entries.sort(key=lambda e: e.id, reverse=True)
return mixed_entries[:10]
105. class Feed(object):
def get_entries(self, limit=10):
ids = exc_sqls("select id from entry where feed_id=
%s order by id desc limit %s", (self.id, limit))
return [Entry.get(id) for id in ids]
class FeedCollection(object):
def get_entries(self, limit=10):
mixed_entries = []
for feed in self.feeds:
entries = feed.get_entries(limit=limit)
mixed_entries += entries
mixed_entries.sort(key=lambda e: e.id, reverse=True)
return mixed_entries[:10]
106. class Feed(object):
def get_entries(self, limit=10):
ids = exc_sqls("select id from entry where feed_id=
%s order by id desc limit %s", (self.id, limit))
return [Entry.get(id) for id in ids]
class FeedCollection(object):
=
def get_entries(self, limit=10):
len(self.feeds) * limit
mixed_entries = []
for feed in self.feeds:
entries = feed.get_entries(limit=limit)
mixed_entries += entries
mixed_entries.sort(key=lambda e: e.id, reverse=True)
return mixed_entries[:10]
107. class Feed(object):
def get_entries(self, limit=10):
ids = exc_sqls("select id from entry where feed_id=
%s order by id desc limit %s", (self.id, limit))
return [Entry.get(id) for id in ids]
class FeedCollection(object):
Entry.get =
def get_entries(self, limit=10):
len(self.feeds-1) * limit
mixed_entries = []
for feed in self.feeds:
entries = feed.get_entries(limit=limit)
mixed_entries += entries
mixed_entries.sort(key=lambda e: e.id, reverse=True)
return mixed_entries[:10]
108. iterator and generator
def fib():
x, y = 1, 1
while True:
yield x
x, y = y, x+y
def odd(seq):
return (n for n in seq if n%2)
def less_than(seq, upper_limit):
for number in seq:
if number >= upper_limit:
break
yield number
print sum(odd(less_than(fib(), 4000000)))
109. itertools
• count([n]) --> n, n+1, n+2
• cycle(p) --> p0, p1, ... plast, p0, p1, ...
• repeat(elem [,n]) --> elem, elem, elem, ...
endless or up to n times
• izip(p, q, ...) --> (p[0], q[0]), (p[1],
q[1]), ...
• islice(seq, [start,] stop [, step]) -->
elements from seq[start:stop:step]
• ... and more ...
110. class Feed(object):
def iter_entries(self):
start_id = sys.maxint
while True:
entry_ids = exc_sqls("select id from entry where
feed_id=%s and id<%s order by id desc limit 5", (self.id, start_id))
if not entry_ids:
break
for entry_id in entry_ids:
yield Entry.get(entry_id)
start_id = entry_ids[-1]
class FeedCollection(object):
def iter_entries(self):
return imerge(*[feed.iter_entries() for feed in self.feeds])
def get_entries(self, limit=10):
return list(islice(self.iter_entries(), limit))
111. class Feed(object):
def iter_entries(self):
start_id = sys.maxint
while True:
entry_ids = exc_sqls("select id from entry where
feed_id=%s and id<%s order by id desc limit 5", (self.id, start_id))
if not entry_ids:
break
for entry_id in entry_ids:
yield Entry.get(entry_id)
start_id = entry_ids[-1]
class FeedCollection(object):
def iter_entries(self):
return imerge(*[feed.iter_entries() for feed in self.feeds])
def get_entries(self, limit=10):
return list(islice(self.iter_entries(), limit))
112. class Feed(object):
def iter_entries(self):
start_id = sys.maxint
while True:
entry_ids = exc_sqls("select id from entry where
feed_id=%s and id<%s order by id desc limit 5", (self.id, start_id))
if not entry_ids:
break
for entry_id in entry_ids:
yield Entry.get(entry_id)
start_id = entry_ids[-1]
class FeedCollection(object):
def iter_entries(self):
return imerge(*[feed.iter_entries() for feed in self.feeds])
def get_entries(self, limit=10):
return list(islice(self.iter_entries(), limit))
113. class Feed(object):
def iter_entries(self):
start_id = sys.maxint
while True:
entry_ids = exc_sqls("select id from entry where
feed_id=%s and id<%s order by id desc limit 5", (self.id, start_id))
if not entry_ids:
break
for entry_id in entry_ids:
yield Entry.get(entry_id)
start_id = entry_ids[-1]
class FeedCollection(object):
def iter_entries(self):
return imerge(*[feed.iter_entries() for feed in self.feeds])
def get_entries(self, limit=10):
return list(islice(self.iter_entries(), limit))
114. class Feed(object):
def iter_entries(self):
start_id = sys.maxint
while True:
entry_ids = exc_sqls("select id from entry where
feed_id=%s and id<%s order by id desc limit 5", (self.id, start_id))
if not entry_ids:
break
for entry_id in entry_ids:
yield Entry.get(entry_id)
start_id = entry_ids[-1]
class FeedCollection(object):
def iter_entries(self):
return imerge(*[feed.iter_entries() for feed in self.feeds])
def get_entries(self, limit=10):
return list(islice(self.iter_entries(), limit))
115. class Feed(object):
def iter_entries(self):
start_id = sys.maxint
while True:
entry_ids = exc_sqls("select id from entry where
feed_id=%s and id<%s order by id desc limit 5", (self.id, start_id))
if not entry_ids:
break
for entry_id in entry_ids: =
yield Entry.get(entry_id)
len(self.feeds) * 5 ~
start_id = entry_ids[-1]
len(self.feeds)*5 + limit -5
class FeedCollection(object):
def iter_entries(self):
return imerge(*[feed.iter_entries() for feed in self.feeds])
def get_entries(self, limit=10):
return list(islice(self.iter_entries(), limit))
116. class Feed(object):
def iter_entries(self):
start_id = sys.maxint
while True:
entry_ids = exc_sqls("select id from entry where
feed_id=%s and id<%s order by id desc limit 5", (self.id, start_id))
if not entry_ids:
break
for entry_id in entry_ids:
yield Entry.get(entry_id)
start_id = entry_ids[-1] Entry.get =
0 ~ len(self.feeds)-1
class FeedCollection(object):
def iter_entries(self):
return imerge(*[feed.iter_entries() for feed in self.feeds])
def get_entries(self, limit=10):
return list(islice(self.iter_entries(), limit))
119. class User(object):
def __init__(self, id, username, screen_name, sig):
self.id = id
self.username = username
self.screen_name = screen_name
self.sig = sig
user = User('1002211', 'hongqn', 'hongqn', "
")
120. cPickle vs. marshal
$ python -m timeit -s '
> from user import user
> from cPickle import dumps, loads
> s = dumps(user, 2)'
> 'loads(s)'
100000 loops, best of 3: 6.6 usec per loop
$ python -m timeit -s '
> from user import user
> from marshal import dumps, loads
> d = (user.id, user.username, user.screen_name, user.sig)
> s = dumps(d, 2)' 'loads(s)'
1000000 loops, best of 3: 0.9 usec per loop
121. cPickle vs. marshal
$ python -m timeit -s '
> from user import user
> from cPickle import dumps, loads
> s = dumps(user, 2)'
> 'loads(s)'
7
100000 loops, best of 3: 6.6 usec per loop
$ python -m timeit -s '
> from user import user
> from marshal import dumps, loads
> d = (user.id, user.username, user.screen_name, user.sig)
> s = dumps(d, 2)' 'loads(s)'
1000000 loops, best of 3: 0.9 usec per loop
122. cPickle vs. marshal
$ python -m timeit -s '
> from user import user
> from cPickle import dumps, loads
> s = dumps(user, 2)'
> 'loads(s)'
7
100000 loops, best of 3: 6.6 usec per loop
$ python -m timeit -s '
> from user import user
> from marshal import dumps, loads
> d = (user.id, user.username, user.screen_name, user.sig)
> s = dumps(d, 2)' 'loads(s)'
1000000 loops, best of 3: 0.9 usec per loop
123. cPickle vs. marshal
$ python -c timeit
'
> import cPickle, marshal
> from user import user
> print "pickle:", len(cPickle.dumps(user, 2))
> print "marshal:", len(marshal.dumps((user.id,
> user.username, user.screen_name, user.sig), 2))'
pickle: 129
marshal: 74
43%
124. cPickle vs. marshal
$ python -c timeit
'
> import cPickle, marshal
> from user import user
> print "pickle:", len(cPickle.dumps(user, 2))
> print "marshal:", len(marshal.dumps((user.id,
> user.username, user.screen_name, user.sig), 2))'
pickle: 129
marshal: 74
43%
125. namedtuple
from collections import namedtuple
User = namedtuple('User', 'id username screen_name sig')
user = User('1002211', 'hongqn', 'hongqn', sig="
")
user.username
-> 'hongqn'
126. __metaclass__
class User(tuple):
__metaclass__ = NamedTupleMetaClass
__attrs__ = ['id', 'username', 'screen_name', 'sig']
user = User('1002211', 'hongqn', 'hongqn', sig="
")
s = marshal.dumps(user.__marshal__())
User.__load_marshal__(marshal.loads(s))
127. from operator import itemgetter
class NamedTupleMetaClass(type):
def __new__(mcs, name, bases, dict):
assert bases == (tuple,)
for i, a in enumerate(dict['__attrs__']):
dict[a] = property(itemgetter(i))
dict['__slots__'] = ()
dict['__marshal__'] = tuple
dict['__load_marshal__'] = classmethod(tuple.__new__)
dict['__getnewargs__'] = lambda self: tuple(self)
argtxt = repr(tuple(attrs)).replace("'", "")[1:-1]
template = """def newfunc(cls, %(argtxt)s):
return tuple.__new__(cls, (%(argtxt)s))""" % locals()
namespace = {}
exec template in namespace
dict['__new__'] = namespace['newfunc']
return type.__new__(mcs, name, bases, dict)