分类目录归档:Python

Python — imaplib IMAP example with Gmail

I couldn’t find all that much information about IMAP on the web, other than the RFC3501.

The IMAP protocol document is absoutely key to understanding the commands available, but let me skip attempting to explain and just lead by example where I can point out the common gotchas I ran into.

Logging in to the inbox

1
2
3
4
5
6
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myusername@gmail.com', 'mypassword')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.

Getting all mail and fetching the latest

Let’s start by searching our inbox for all mail with the search function.
Use the built in keyword “ALL” to get all results (documented in RFC3501).

We’re going to extract the data we need from the response, then fetch the mail via the ID we just received.

1
2
3
4
5
6
7
8
9
10
result, data = mail.search(None, "ALL")
ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest
result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID
raw_email = data[0][1] # here's the body, which is raw text of the whole email
# including headers and alternate payloads

Using UIDs instead of volatile sequential ids

继续阅读

How to:Python

1、django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured.

You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

>>> from django.conf import settings
>>> settings.configure()
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()

use MySQL on Django with Python3.6

My environment: Windows 10, Python 3.6, Django 1.11.4., PyMySQL 0.6.1, MySQL Server 5.7 on Windows

How to make it work:

  1. Install PyMySQL version 0.7.11 (https://github.com/PyMySQL/PyMySQL/): you can install it either by using pip, i.e. : pip install PyMySQL or by manually downloading the package; there is a good documentation on their website on how to do that.
  2. Open your Django App __init__.py and paste the following lines:
    import pymysql
    pymysql.install_as_MySQLdb() 
    
  3. Now, open settings.py and make sure your DATABASE property looks like this:
    DATABASES = {
       'default': {
           'ENGINE': 'django.db.backends.mysql',
           'NAME': 'mydb',
           'USER': 'dbuser',
           'PASSWORD': 'dbpassword',
           'HOST': 'dbhost',
           'PORT': '3306'
        }
    }
    
  4. That’s it, you should be able to execute python manage.py syncdb to init your MySQL DB; see the sample output below:
    Creating tables ...
    Creating table django_admin_log
    Creating table auth_permission
    Creating table auth_group_permissions
    ...
    ...
    Creating table socialaccount_socialtoken
    
    You just installed Django's auth system, which means you don't have any superusers defined.
    ...
    
  5. you should be able to execute python manage.py migrate to creates any necessary database tables according
    to the database settings in your mysite/settings.py file and the database migrations shipped with the app; see the sample output below:

    
    Operations to perform:
      Apply all migrations: admin, auth, contenttypes, sessions
    Running migrations:
      Applying contenttypes.0001_initial... OK
      Applying auth.0001_initial... OK
      Applying admin.0001_initial... OK
      Applying admin.0002_logentry_remove_auto_add... OK
      Applying contenttypes.0002_remove_content_type_name... OK
      Applying auth.0002_alter_permission_name_max_length... OK
      Applying auth.0003_alter_user_email_max_length... OK
      Applying auth.0004_alter_user_username_opts... OK
      Applying auth.0005_alter_user_last_login_null... OK
      Applying auth.0006_require_contenttypes_0002... OK
      Applying auth.0007_alter_validators_add_error_messages... OK
      Applying auth.0008_alter_user_username_max_length... OK
      Applying sessions.0001_initial... OK
    

File System Redirector

The %windir%\System32 directory is reserved for 64-bit applications. Most DLL file names were not changed when 64-bit versions of the DLLs were created, so 32-bit versions of the DLLs are stored in a different directory. WOW64 hides this difference by using a file system redirector.

In most cases, whenever a 32-bit application attempts to access %windir%\System32, the access is redirected to %windir%\SysWOW64. Access to %windir%\lastgood\system32 is redirected to %windir%\lastgood\SysWOW64. Access to %windir%\regedit.exe is redirected to %windir%\SysWOW64\regedit.exe.

If the access causes the system to display the UAC prompt, redirection does not occur. Instead, the 64-bit version of the requested file is launched. To prevent this problem, either specify the SysWOW64 directory to avoid redirection and ensure access to the 32-bit version of the file, or run the 32-bit application with administrator privileges so the UAC prompt is not displayed. 继续阅读

Python fabric远程自动部署简介

Fabric是一个Python(2.5-2.7)库,用于简化使用SSH的应用程序部署或系统管理任务。

它提供的操作包括:执行本地或远程shell命令,上传/下载文件,以及其他辅助功能,如提示用户输入、中止执行等。

本文主要介绍CentOS 6.3上使用fabric进行自动部署的基本方法。 继续阅读

Python:使用代理proxy爬虫

Python:使用代理proxy爬虫

inotify+rsync实现触发式文件同步

一般我们把rsync放在crontab里进行定时文件同步,同步的延时有可能会比我们想象的长。这里你可以使用inotify来对文件进行监控,实现触发式同步。

在安装inotify-tools前请先确认你的linux内核是否打到了2.6.13,并且在编译时开启了CONFIG_INOTIFY选项。你可以按下面的方式简单的确认这一点:ls /proc/sys/fs/inotify,如果支持的话会有 max_queued_events,max_user_instances,max_user_watches三项。 继续阅读