实习日记3

 

Integrating python and java:

Py4J: Py4J enables Python programs runningin a Python interpreter to dynamically access Java objects in a JVM. Methodsare called as if the Java objects resided in the Python interpreter and Javacollections can be accessed through standard Python collection methods. Py4Jalso enables Java programs to call back Python objects.


Here is a brief example of what you

can do with Py4J. The following Python program creates a java.util.Random instance from a JVM and calls some of its

methods. It also accesses a custom Java class, AdditionApplicationto add the generated numbers.

>>>from py4j.java_gateway importJavaGateway

>>>gateway =JavaGateway()                   # connect to the JVM

>>>random = gateway.jvm.java.util.Random()   # create a java.util.Random instance

>>>number1 = random.nextInt(10)              # call the Random.nextInt method

>>>number2 = random.nextInt(10)

>>>print(number1, number2)

(2, 7)

>>>addition_app = gateway.entry_point               # get the AdditionApplication instance

>>>value = addition_app.addition(number1,

number2)) # call the addition

method

>>>print(value)

9

This is the Java program that was executing

at the same time (no code was generated and no tool was required to run these

programs). The AdditionApplication

app instance is

the gateway.entry_pointin the previous code snippet.Note that the Java program must be started before executing the Python codeabove. In other words, the Py4J does not start a JVM.

import py4j.GatewayServer;


public class AdditionApplication {


  public int addition(intfirst, int second) {

    returnfirst + second;

  }


  public static void main(String[] args) {

    AdditionApplication app= new AdditionApplication();

    // app is now the gateway.entry_point

    GatewayServer server= new GatewayServer(app);

    server.start();

  }

}

Source:https://www.py4j.org/index.html

 

 

SQLalchemy:SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that givesapplication developers the full power and flexibility of SQL.

SQLAlchemy连接数据库(MyAQL, SQLite, PostgreSQL),创建数据表

SQLAlchemy中的一个session可以看作是一个transaction,每个操作(基本上)对应一条或者多条SQL语句,这些SQL语句需要发送到数据库服务器才能被真正执行,而整个transaction需要commit才能真正生效,如果没有提交,一旦程序挂了,所有未提交的事务都会被回滚到事务开始之前的状态。

Commit就是告诉数据库服务器提交事务

Flush预提交,等于提交到数据库内存,还未写入数据库文件;

Commit就是把内存里面的东西直接写入,可以提供查询了。

 

 

Psycopg2是python的postgresql数据库接口

 

 

ORM

Object Relational Mapping 对象关系映射。简单来说,ORM将数据库中的表与面向对象语言中的类建立了一种对应关系。这样,我们要操作数据库,数据库中的表或者表中的一条记录就可以直接通过操作类或者类实例来完成。

 

连接数据库:

Fromsqlalchemy import create_engine

Engine= create_engine(‘mysql+mysqldb://root@localhost:3306/blog’)

Print(engine)

连接了默认运行在3306端口的MySQL中的blog数据库

https://www.cnblogs.com/mrchige/p/6389588.html

 

 

 

 

 

 

 

CRUD是指在做计算处理时的增加(Create)、读取查询(Retrieve)、更新(Update)和删除(Delete).CRUD主要被用在描述软件系统中数据库或者持久层的基本操作功能。

增删改查

 

 

 

 

 

 

APScheduler是一个python第三方库,用来提供python后台程序。包含四个组件,分别是:

Trigger:任务触发器组件,提供任务触发方式

Job stores:任务商店组件,提供任务保存方式

Executors:任务调度组件,提供任务调度方式

Schedulers:任务调度组件,提供任务工作方式

from apscheduler.schedulers.blocking importBlockingScheduler

importtime


# 实例化一个调度器

scheduler =BlockingScheduler()


def job1():

    print "%s: 执行任务"  % time.asctime()


# 添加任务并设置触发方式为3s一次

scheduler.add_job(job1,'interval', seconds=3)


# 开始运行调度器

scheduler.start()



OBS:

桶bucket是OBS 中存储对象的容器。对象存储提供了基于桶和对象的扁平化存储方式,桶中的所有对象都处于同一逻辑层级,去除了文件系统中多层级树形目录结构。

AK Access Key ID: 访问密钥ID。与私有访问密钥关联的唯一标识符;访问密钥ID和私有访问密钥一起使用,对请求进行加密签名。

SK Secret Access

Key:与访问密钥ID结合使用的密钥,对请求进行加密签名,可标识发送方,并防止请求被修改。



Uuid 通用唯一识别码(Universally Unique Identifier, 缩写UUID)是用于计算机体系中以识别信息数目的一个128位标识符

相关术语:全局唯一标识符(GUID)根据标准方法生成,不依赖中央机构的注册和分配,UUID具有唯一性,这与其他大多数编号方案不同。重复UUID码概率接近零,可以忽略不计。



IAM identity andaccess management is a framework of policies and technologies for ensuring thatthe proper people in an enterprise have the appropriate access to technologyresources.




Type 不会认为子类是父类

Isinstance 会认为子类是父类

 

 

 

 

 

 

deffunc(*num, **words):

       print(“num:”+str(num))

       print(“word:”+str(words))

func(1,3,5,7,word=”pyhton”,another_word=”java”)

#num:(1,3,5,7)

#words:{‘word’:’python’, ‘another_word’:’java’}

*用来表示接受一个tuple,**用来表示字典

 

 

 

 

Connectionreset by peer:

The

remote server has sent you a RST packet,whichindicates an immediate dropping of the connection, rather than the usualhandshake. This bypasses the normal half-closed state transition. I like thisdescription: connection reset by peer is the TCP/IP equivalent of slamming thephone back on the hook. It’s more polite than merely not replying, leaving onehanging. But it’s not the FIN-ACK expected of the truly polite TCP/IPconverseur.

 

 

Pycharm整体缩进的快捷键(sublime不适用)

选中多行,按tab进行缩进,按tab+shift去除缩进

 

Pythonmock

Mock是python中一个用于支持单元测试的库,它的主要功能是使用mock对象代替掉指定的python对象,以到达模拟对象的行为。

Fromunittest import mock

Importrequests

Def c(url):

       Resp = requests.get(url)

       # further process with resp

使用一个mock对象替换掉上面的requests.get函数,然后执行函数c时,c调用requests.get的返回值就能够由我们的mock对象来决定,而不需要服务器的参与。

Mock对象是mock模块中最重要的概念,mock对象就是Mock模块中的一个类的实例,这个类的实例可以用来替换其他的python对象,来达到模拟的效果,mock类的定义如下:

ClassMock(…………)

Mock对象的一般用法是这样的:

[if !supportLists]1.      [endif]找到你要替换的对象,这个对象可以是一个类,或者一个函数,或者是一个类实例。

[if !supportLists]2.      [endif]然后实例化MOCK类得到一个mock对象,并且设置这个mock对象的行为,比如被调用的时候返回什么值,被访问成员的时候返回什么值等。

[if !supportLists]3.      [endif]使用这个mock对象替换掉我们想替换的对象,也就是步骤1中确定的对象。

[if !supportLists]4.      [endif]之后就可以开始写测试代码,这个时候我们可以保证我们替换掉的对象在测试用例执行的过程中行为和我们预设的一样。

Mock类定义的参数:name;这个是用来命名一个mock对象,只是起到标识的作用,当你print一个mock对象的时候,可以看到它的name

       Return_value:这个字段可以指定一个值,(或者对象),当mock对象被调用时,如果side_effect函数返回的是DEFAULT,则对mock对象的调用会返回return_value指定的值

       Side_effect:这个参数指向一个可调用的对象,一般就是函数,当mock对象被调用时,如果该函数返回值不是DEFAULT时,那么以该函数的返回值作为mock对象调用的返回值。

注意,如果测试对象中有celery方法时,需要对其进行mock处理

Mock对象的自动创建:当访问一个mock对象不存在的属性时,mock会自动建立一个子mock对象,并且把正在访问的属性指向它,这个功能对于实现多级属性的mock很方便。

 

Mock:https://segmentfault.com/a/1190000002965620

 

Pytest:https://www.jianshu.com/p/a754e3d47671














一个debug:

Importerror: cannot import name‘thread_local’ from ‘IAM’ (unknown location)

The name of the module is the problem,python already has a module named IAM. I changed the name into IAMfile to avoidthis error.






From datetime import date

Import time

D1 = date(2018, 7, 31)

D2 = date.today()

D3 = date.fromtimestamp(time.time())


获取星期。标准格式1-7

D2.isoweekday()

获取星期,格式0-6

D2.weekday()

格式化显示

D3.strftime(‘%Y/%m/%d’)



From datetime import time

T = time(1,2,3) #01:02:03

格式化显示

t.strftime(‘%H:%M:%S’)


from datetime import datetime

本地当前时间,带时区

dt3 = datetime.now()


from datetime import datetime, timedelta

d1 = datetime(2018, 7, 31, 20, 49, 55)

d2 = datetime(2018, 7, 31, 20, 55, 23)

delta2 = timedelta(days=1,hours=1)

d3 = d1 + delta2

提取天数:delta2.days

提取除天数以外的秒数:delta2.seconds

总共的秒数delta2.total_seconds()

两个date或者datetime对象相减时可以返回一个timedelta对象

你可能感兴趣的:(实习日记3)