精华内容
下载资源
问答
  • 2021-03-17 19:56:27

    有时候要从第三方导入数据,一般量都比较大,除了方法用异步线程@Async之外,如果每条记录都调用一次save显然对数据库压力很大。可以使用JPA的批量保存方法saveAll(Iterable entities)。

    由于JPA的批量保存和批量修改是同一个方法,所以本文也适用批量修改操作。

    一、Entity改造

    增加3个注解,方便在Controller类build方式构造对象。

    @Builder

    @NoArgsConstructor

    @AllArgsConstructor

    完整注解:

    @Data

    @Builder

    @NoArgsConstructor

    @AllArgsConstructor

    @ApiModel("休息日,休息日可能不处理业务,备用")

    @Entity

    @Table(name = "bz_setup_restday", schema = "bankrouter")

    public class BzSetupRestdayEntity implements Serializable {

    ......

    二、Repository

    package com.pay.payee.repository;

    import com.pay.payee.entity.BzSetupRestdayEntity;

    import org.springframework.data.jpa.repository.JpaRepository;

    import java.util.Date;

    /**

    *

    休息日,休息日可能不处理业务,备用(BzSetupRestday)表数据库访问层

    *

    * @author 郭秀志 jbcode@126.com

    * @since 2020-05-08 23:50:43

    */

    public interface BzSetupRestdayRepository extends JpaRepository {

    }

    三、Service实现类

    关键方法saveAll(Iterable entities)。

    package com.pay.payee.service.impl;

    import com.pay.payee.entity.BzSetupRestdayEntity;

    import com.pay.payee.repository.BzSetupRestdayRepository;

    import com.pay.payee.service.IBzSetupRestdayService;

    import org.springframework.beans.factory.annotation.Autowired;

    import org.springframework.stereotype.Service;

    import java.util.Date;

    import java.util.List;

    import java.util.Optional;

    /**

    *

    休息日,休息日可能不处理业务,备用(BzSetupRestday)表服务实现类

    *

    * @author 郭秀志 jbcode@126.com

    * @since 2020-05-08 23:50:43

    */

    @Service("bzSetupRestdayService")

    public class BzSetupRestdayServiceImpl implements IBzSetupRestdayService {

    @Autowired

    private BzSetupRestdayRepository bzSetupRestdayRepository;

    @Override

    public void save(BzSetupRestdayEntity bzSetupRestdayEntity) {

    bzSetupRestdayRepository.save(bzSetupRestdayEntity);

    }

    public List saveAll(Iterable entities) {

    return bzSetupRestdayRepository.saveAll(entities);

    }

    }

    四、Controller

    60000条数据使用方法saveAll(Iterable entities)进行批量保存。

    package com.pay.payee.controller;

    import com.pay.payee.entity.BzSetupRestdayEntity;

    import com.pay.payee.service.IBzSetupRestdayService;

    import org.springframework.web.bind.annotation.GetMapping;

    import org.springframework.web.bind.annotation.RequestMapping;

    import org.springframework.web.bind.annotation.RestController;

    import javax.annotation.Resource;

    import java.util.ArrayList;

    import java.util.Date;

    import java.util.List;

    /**

    * 休息日,休息日可能不处理业务,备用(BzSetupRestday)表控制层

    *

    * @author 郭秀志 jbcode@126.com

    * @since 2020-05-08 23:50:43

    */

    @RestController

    @RequestMapping("/bzSetupRestday")

    public class BzSetupRestdayController {

    /**

    * 服务对象

    */

    @Resource

    private IBzSetupRestdayService bzSetupRestdayService;

    /*

    * @Description 批量保存

    * @Param [entities]

    * @return java.util.List

    */

    @GetMapping("/saveAll")

    public List saveAll() {

    long begin = System.currentTimeMillis();

    List list = new ArrayList();

    for (int i = 0; i < 60000; i++) {

    BzSetupRestdayEntity build = BzSetupRestdayEntity.builder().groupId("1").restDate(new Date()).useType("2").build();

    list.add(build);

    }

    List sList = (List) bzSetupRestdayService.saveAll(list);

    long end = System.currentTimeMillis();

    System.out.println("时长:" + (end - begin));

    return sList;

    }

    }

    五、调用url测试

    http://localhost:8555/bzSetupRestday/saveAll

    控制台输出耗时(毫秒):时长:15958

    网上个别人遇到saveAll速度慢,添加了如下配置信息解决。我实测速度无差别。

    spring:

    jpa:

    properties:

    hibernate:

    #打印执行时间统计信息

    generate_statistics: true

    jdbc:

    #每批500条提交

    batch_size: 500

    batch_versioned_data: true

    order_inserts: true

    order_updates: true

    六、批量保存优化

    6.1 背景

    有次实践是有20万左右的数据要批量的插入,速度非常慢,发现打印出来的sql是先select一次,再insert。

    6.2 速度慢原因

    原生的saveAll()方法可以保证程序的正确性,但是如果数据量比较大效率低,看下源码就知道其原理是 for 循环每一条数据,然后先select一次,如果数据库存在,则update。如果不存在,则insert。

    6.3. saveAll源码

    SimpleJpaRepository的saveAll(Iterable entities)方法源码如下:

    @Transactional

    public List saveAll(Iterable entities) {

    Assert.notNull(entities, "Entities must not be null!");

    List result = new ArrayList();

    Iterator var3 = entities.iterator();

    while(var3.hasNext()) {

    S entity = var3.next();

    result.add(this.save(entity));//save方法是核心逻辑

    }

    return result;

    }

    @Transactional

    public S save(S entity) {

    if (this.entityInformation.isNew(entity)) {

    this.em.persist(entity);

    return entity;

    } else {

    return this.em.merge(entity);

    }

    }

    6.4 解决方案

    6.4.1 批量插入

    解决方案是自己用em进行持久化插入,省了一步查询操作。

    @PersistenceContext

    private EntityManager entityManager;

    @Override

    @Transactional(rollbackFor = Exception.class)

    public void addBatch(List list) {

    for (ProjectApplyDO projectApplyDO : list) {

    entityManager.persist(projectApplyDO);//insert插入操作

    }

    entityManager.flush();

    entityManager.clear();

    }

    6.4.2 批量更新

    在确保数据已经存在的情况下,如果是批量更新可以如下代码代替上面的entityManager.persist(projectApplyDO);语句:

    entityManager.merge(projectApplyDO);//update更新操作

    更多相关内容
  • DataSave DataSave

    2018-05-04 11:16:14
    DataSave DataSave DataSave DataSave DataSave DataSave
  • save-ps-to-svg1.0.jsx

    2017-06-12 17:43:43
    直接 PhotoShop 直接将形状文件转化导出为 SVG路径的脚本
  • save-ps-to-svg 1.0.zip

    2017-06-12 19:27:13
    支持 PhotoShop 将形状图片转化为 svg路径的脚本
  • DIIIROS.SaveEdit_1.3.18.142

    2015-11-21 14:57:21
    DIIIROS.SaveEdit_1.3.18.142
  • Python config.save方法代码示例

    千次阅读 2020-11-30 13:10:18
    Python config.save方法代码示例

    本文整理汇总了Python中config.save方法的典型用法代码示例。如果您正苦于以下问题:Python config.save方法的具体用法?Python config.save怎么用?Python config.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块config的用法示例。

    在下文中一共展示了config.save方法的22个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

    示例1: ask_user

    ​点赞 3

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def ask_user(preferences = {}):

    def add_argument(name, help, **kwargs):

    kwargs['required'] = kwargs.get('required', not (name in preferences))

    kwargs['default'] = kwargs.get('default', preferences.get(name, None))

    parser.add_argument('--' + name, help=help, **kwargs)

    parser = argparse.ArgumentParser(description="Access MeuAlelo system to extract this month's operations")

    add_argument('cpf', "CPF with only numbers")

    add_argument('password', "Password used to access the system")

    add_argument('card', "Which card from the list we want to access", type=int, default=0)

    add_argument('save', "If present saves the provided configurations in an init file",

    required=False, action="store_true")

    add_argument('month', "Specify for which month transactions must be converted",

    required=False, type=int)

    return vars(parser.parse_args())

    开发者ID:dantas,项目名称:alelo_ofx,代码行数:19,

    示例2: handleKlok

    ​点赞 3

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def handleKlok(self):

    neo = self.neo

    if config.dirty:

    self.updateFromConfig()

    config.save()

    now = time.localtime()

    hour = (now[3] + config.get("timeoffset",1) ) % 12

    h = hour * 5 + (now[4] + 6)/12;

    h = int (h % 60)

    neo.clearBuffer()

    neo.setPixel(29, self.stateColor)

    neo.setPixel(31, self.stateColor)

    neo.setPixel( 0, self.qColor);

    neo.setPixel( 15, self.qColor);

    neo.setPixel( 30, self.qColor);

    neo.setPixel( 45, self.qColor);

    neo.addPixel(now[5] , self.sColor)

    neo.addPixel(now[4], self.mColor)

    neo.addPixel(h, self.hColor)

    neo.writeBuffer()

    开发者ID:smeenka,项目名称:esp32,代码行数:23,

    示例3: startap

    ​点赞 3

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def startap(ssid = None,pw = None):

    if ssid:

    config.put("ap_ssid",ssid)

    ssid = config.get("ap_ssid","micropython2")

    if pw:

    config.put("ap_pw",pw)

    pw = config.get("ap_pw","12345678")

    config.save()

    log.info("Starting AP with ssid:%s",ssid)

    ap.active(False)

    time.sleep_ms(100)

    ap.active(True)

    time.sleep_ms(100)

    ap.config(essid=ssid, channel=11,password=pw)

    开发者ID:smeenka,项目名称:esp32,代码行数:19,

    示例4: save_config

    ​点赞 3

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def save_config(self, *args):

    header = "save_config(): "

    print header," saving..."

    sys.stdout.flush()

    # read parameters from GUI first!

    self.get_param()

    config.save(self.param)

    print header," done!"

    sys.stdout.flush()

    return

    # ------------------------------------------------------------------

    开发者ID:sid5432,项目名称:pm-fiber-birefringence,代码行数:19,

    示例5: main

    ​点赞 3

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def main():

    PiCamera.set(exposure=config.exposure, resolution=config.resolution)

    config.resolution = PiCamera.getResolution()

    config.degPerPxl = np.divide(config.nativeAngle, config.resolution)

    if not config.edited:

    GripRunner.editCode()

    frameNum = 1

    while True:

    image = PiCamera.getImage()

    contours = GripRunner.run(image)

    targets = filterContoursFancy(contours, image=image)

    isVisible, angleToGoal, distance = findSpike(targets)

    if config.debug:

    Printing.printResults(contours=contours, distance=distance, angleToGoal=angleToGoal, isVisible=isVisible)

    if config.save:

    Printing.drawImage(image, contours, targets, center)

    Printing.save(image)

    try:

    NetworkTabling.publishToTables(isVisible=isVisible, angleToGoal=angleToGoal, distance=distance, frameNum=frameNum)

    except Exception as error:

    if config.debug:

    print error

    frameNum += 1

    开发者ID:RoboticsTeam4904,项目名称:2017-Vision,代码行数:25,

    示例6: save_if_necessary

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def save_if_necessary(preferences):

    if preferences['save']:

    del preferences['save']

    del preferences['month']

    config.save(preferences)

    开发者ID:dantas,项目名称:alelo_ofx,代码行数:7,

    示例7: load_preferences

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def load_preferences():

    preferences = config.read()

    preferences['month'] = None

    preferences['card'] = int(preferences.get('card', 0))

    preferences['save'] = False

    return preferences

    开发者ID:dantas,项目名称:alelo_ofx,代码行数:8,

    示例8: train

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def train():

    cleanup.cleanup()

    c.save(c.work_dir)

    data_loader = TextLoader(c.work_dir, c.batch_size, c.seq_length)

    with open(os.path.join(c.work_dir, 'chars_vocab.pkl'), 'wb') as f:

    cPickle.dump((data_loader.chars, data_loader.vocab), f)

    model = Model(c.rnn_size, c.num_layers, len(data_loader.chars), c.grad_clip, c.batch_size, c.seq_length)

    with tf.Session() as sess:

    tf.initialize_all_variables().run()

    saver = tf.train.Saver(tf.all_variables())

    for e in range(c.num_epochs):

    sess.run(tf.assign(model.lr, c.learning_rate * (c.decay_rate ** e)))

    data_loader.reset_batch_pointer()

    state = model.initial_state.eval()

    for b in range(data_loader.num_batches):

    start = time.time()

    x, y = data_loader.next_batch()

    feed = {model.input_data: x, model.targets: y, model.initial_state: state}

    train_loss, state, _ = sess.run([model.cost, model.final_state, model.train_op], feed)

    end = time.time()

    print("{}/{} (epoch {}), train_loss = {:.3f}, time/batch = {:.3f}"

    .format(e * data_loader.num_batches + b,

    c.num_epochs * data_loader.num_batches,

    e, train_loss, end - start))

    if (e * data_loader.num_batches + b) % c.save_every == 0:

    checkpoint_path = os.path.join(c.work_dir, 'model.ckpt')

    saver.save(sess, checkpoint_path, global_step=e * data_loader.num_batches + b)

    print("model saved to {}".format(checkpoint_path))

    开发者ID:dvictor,项目名称:lstm-poetry,代码行数:33,

    示例9: connect2ap

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def connect2ap(ssid= None,pw = None):

    """ If pw is None get the password from the config file

    If pw is not None, write ssid,pw to the config file

    If ip is None in config file choose dhcp config

    else get ip.

    If gw is None it is assumed as 192.168.2.254,

    If dns is None it is assumed as 192.168.2.254,

    Deactivate the wlan, wait 1 second and activate with given ssid and pw

    """

    log.info("Connecting to ap %s",ssid)

    if not ssid:

    ssid = config.get("ssid","xxxx")

    else:

    config.put("ssid",ssid)

    if not pw:

    pw = config.get(ssid,"geheim")

    else:

    config.put(ssid,pw)

    ip = config.get("wlan_ip")

    gw = config.get("wlan_gw","192.168.2.254")

    dns = config.get("wlan_dns","192.168.2.254")

    config.save()

    wlan.active(False)

    wlan.active(True)

    if ip:

    wconf = ( ip,'255.255.255.0',gw,dns)

    wlan.ifconfig( wconf )

    wlan.connect(ssid,pw)

    开发者ID:smeenka,项目名称:esp32,代码行数:36,

    示例10: on_enable_gae_proxy

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def on_enable_gae_proxy(self, widget=None, data=None):

    win32_proxy_manager.set_proxy("127.0.0.1:8087")

    config.set(["modules", "launcher", "proxy"], "gae")

    config.save()

    开发者ID:yuxiaokui,项目名称:Intranet-Penetration,代码行数:6,

    示例11: on_enable_pac

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def on_enable_pac(self, widget=None, data=None):

    win32_proxy_manager.set_proxy("http://127.0.0.1:8086/proxy.pac")

    config.set(["modules", "launcher", "proxy"], "pac")

    config.save()

    开发者ID:yuxiaokui,项目名称:Intranet-Penetration,代码行数:6,

    示例12: on_disable_proxy

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def on_disable_proxy(self, widget=None, data=None):

    win32_proxy_manager.disable_proxy()

    config.set(["modules", "launcher", "proxy"], "disable")

    config.save()

    开发者ID:yuxiaokui,项目名称:Intranet-Penetration,代码行数:6,

    示例13: process_data_files

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def process_data_files():

    #TODO: fix bug

    #new_config = get_new_new_config()

    #config.load()

    #config.config["modules"]["gae_proxy"]["current_version"] = new_config["modules"]["gae_proxy"]["current_version"]

    #config.config["modules"]["launcher"]["current_version"] = new_config["modules"]["launcher"]["current_version"]

    config.save()

    开发者ID:yuxiaokui,项目名称:Intranet-Penetration,代码行数:9,

    示例14: enableAutoProxy_

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def enableAutoProxy_(self, _):

    try:

    helperDisableGlobalProxy(currentService)

    helperEnableAutoProxy(currentService)

    except:

    disableGlobalProxyCommand = getDisableGlobalProxyCommand(currentService)

    enableAutoProxyCommand = getEnableAutoProxyCommand(currentService)

    executeCommand = 'do shell script "%s;%s" with administrator privileges' % (disableGlobalProxyCommand, enableAutoProxyCommand)

    xlog.info("try enable auto proxy:%s", executeCommand)

    subprocess.call(['osascript', '-e', executeCommand])

    config.set(["modules", "launcher", "proxy"], "pac")

    config.save()

    self.updateStatusBarMenu()

    开发者ID:yuxiaokui,项目名称:Intranet-Penetration,代码行数:16,

    示例15: disableProxy_

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def disableProxy_(self, _):

    try:

    helperDisableAutoProxy(currentService)

    helperDisableGlobalProxy(currentService)

    except:

    disableAutoProxyCommand = getDisableAutoProxyCommand(currentService)

    disableGlobalProxyCommand = getDisableGlobalProxyCommand(currentService)

    executeCommand = 'do shell script "%s;%s" with administrator privileges' % (disableAutoProxyCommand, disableGlobalProxyCommand)

    xlog.info("try disable proxy:%s", executeCommand)

    subprocess.call(['osascript', '-e', executeCommand])

    config.set(["modules", "launcher", "proxy"], "disable")

    config.save()

    self.updateStatusBarMenu()

    开发者ID:yuxiaokui,项目名称:Intranet-Penetration,代码行数:16,

    示例16: ignore_module

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def ignore_module(module, new_version):

    config.set(["modules", module, "ignore_version"], str(new_version))

    config.save()

    开发者ID:yuxiaokui,项目名称:Intranet-Penetration,代码行数:5,

    示例17: check_new_machine

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def check_new_machine():

    current_path = os.path.dirname(os.path.abspath(__file__))

    if current_path != config.get(["update", "last_path"], ""):

    config.set(["update", "last_path"], current_path)

    config.save()

    if sys.platform == "win32" and platform.release() == "XP":

    notify_install_tcpz_for_winXp()

    xlog.info("generate desktop shortcut")

    create_desktop_shortcut()

    开发者ID:yuxiaokui,项目名称:Intranet-Penetration,代码行数:14,

    示例18: generate_new_uuid

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def generate_new_uuid():

    xx_net_uuid = str(uuid.uuid4())

    config.set(["update", "uuid"], xx_net_uuid)

    xlog.info("generate uuid:%s", xx_net_uuid)

    config.save()

    开发者ID:yuxiaokui,项目名称:Intranet-Penetration,代码行数:7,

    示例19: prepare_quit

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def prepare_quit(window):

    """Save the window state and settings file."""

    config.save()

    开发者ID:3D1T0R,项目名称:PortableApps.com-DevelopmentToolkit,代码行数:5,

    示例20: main

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def main():

    WebCam.set(exposure=config.exposure, resolution=config.resolution, contrast=config.contrast, gain=config.gain)

    autocalibrate.calibrate()

    config.resolution = WebCam.getResolution()

    config.degPerPxl = np.divide(config.nativeAngle, config.resolution)

    if not config.edited:

    GripRunner.editCode()

    if config.display:

    cv2.namedWindow("Contours Found")

    frameNum = 1

    while True:

    if NetworkTabling.checkForCalibrate():

    print "CALIBRATING the camera due to button press"

    autocalibrate.calibrate()

    NetworkTabling.putCalibrated()

    image = WebCam.getImage()

    contours = GripRunner.run(image)

    targets = filterContoursFancy(contours)

    isVisible, angleToGoal, distance = findSpike(targets)

    if config.debug:

    Printing.printResults(contours=contours, distance=distance, angleToGoal=angleToGoal, isVisible=isVisible)

    if config.save or config.display:

    Printing.drawImage(image, contours, targets)

    if config.save:

    Printing.save(image)

    if config.display:

    Printing.display(image)

    try:

    NetworkTabling.publishToTables(isVisible=isVisible, angleToGoal=angleToGoal, distance=distance, frameNum=frameNum)

    except Exception as error:

    if config.debug:

    print error

    frameNum += 1

    if display:

    cv2.destroyAllWindows()

    开发者ID:RoboticsTeam4904,项目名称:2017-Vision,代码行数:40,

    示例21: main

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def main():

    if not config.edited:

    GripRunner.editCode()

    if config.display:

    cv2.namedWindow("Contours Found")

    image = cv2.imread(config.sampleImage)

    config.resolution = image.shape[1], image.shape[0]

    config.degPerPxl = np.divide(config.nativeAngle, config.resolution)

    contours = GripRunner.run(image)

    targets = filterContoursFancy(contours, image=image)

    isVisible, angleToGoal, distance = findSpike(targets)

    if config.debug:

    Printing.printResults(contours=contours, distance=distance, angleToGoal=angleToGoal, isVisible=isVisible)

    if config.save or config.display:

    Printing.drawImage(image, contours, targets)

    if config.save:

    Printing.save(image)

    if config.display:

    Printing.display(image)

    try:

    NetworkTabling.publishToTables(isVisible=isVisible, angleToGoal=angleToGoal, distance=distance)

    except Exception as error:

    if config.debug:

    print error

    if config.display:

    cv2.waitKey(0)

    cv2.destroyAllWindows()

    开发者ID:RoboticsTeam4904,项目名称:2017-Vision,代码行数:29,

    示例22: install_module

    ​点赞 2

    # 需要导入模块: import config [as 别名]

    # 或者: from config import save [as 别名]

    def install_module(module, new_version):

    import module_init

    import os, subprocess, sys

    current_path = os.path.dirname(os.path.abspath(__file__))

    new_module_version_path = os.path.abspath( os.path.join(current_path, os.pardir, os.pardir, module, new_version))

    #check path exist

    if not os.path.isdir(new_module_version_path):

    xlog.error("install module %s dir %s not exist", module, new_module_version_path)

    return

    #call setup.py

    setup_script = os.path.join(new_module_version_path, "setup.py")

    if not os.path.isfile(setup_script):

    xlog.warn("update %s fail. setup script %s not exist", module, setup_script)

    return

    config.set(["modules", module, "current_version"], str(new_version))

    config.save()

    if module == "launcher":

    module_init.stop_all()

    import web_control

    web_control.stop()

    subprocess.Popen([sys.executable, setup_script], shell=False)

    os._exit(0)

    else:

    xlog.info("Setup %s version %s ...", module, new_version)

    try:

    module_init.stop(module)

    subprocess.call([sys.executable, setup_script], shell=False)

    xlog.info("Finished new version setup.")

    xlog.info("Restarting new version ...")

    module_init.start(module)

    except Exception as e:

    xlog.error("install module %s %s fail:%s", module, new_version, e)

    开发者ID:yuxiaokui,项目名称:Intranet-Penetration,代码行数:46,

    注:本文中的config.save方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。

    展开全文
  • Django Signals-掌握pre_save和post_save

    千次阅读 2020-07-18 10:18:22
    Use pre_save like a pro) Pre_save (django.db.models.signals.pre_save) is provoked just before the model save() method is called, or you could say model save method is called only after pre_save is ...

    Django, with it’s experienced developer community and regular updates have become a reliable framework to build stable and maintainable websites. Not to forget the easy-to-understand the documentation it provides, makes it easier for the beginners to get their way started in Django

    Django,凭借其经验丰富的开发人员社区和定期更新,已成为构建稳定且可维护的网站的可靠框架。 别忘了它提供的易于理解的文档 ,使初学者更容易在Django中入门

    Without wasting much time on what Django is, let’s jump right into one of it’s most crucial topics- Signals

    在不花太多时间讨论Django是什么的情况下,让我们直接进入它最重要的主题之一- 信号

    什么是信号 (What are Signals)

    Signals, as the name suggests, allow applications to get notified when a certain event occurs. Suppose you want to notify the author of an article whenever someone comments or reacts on the article, but there are several places in your codebase to comment on an article or react on the article. How do you do it? You guessed it right, using signals. Signal hooks some piece of code to be executed as soon as a specific model’s save method is triggered.

    顾名思义,信号允许应用程序在发生特定事件时得到通知 。 假设您想在有人发表评论或对文章做出React时通知文章作者,但是您的代码库中有很多地方可以评论文章或对文章做出React。 你怎么做呢? 您使用信号猜对了。 特定模型的保存方法一被触发,Signal就会钩住要执行的某些代码。

    To have a clearer idea of the above example, let’s define the models.

    为了更清楚地了解上面的示例,让我们定义模型。

    何时使用信号 (When to use Signals)

    Signals are best used when multiple pieces of code are interested in the same model instance events. To understand model instance events in simpler terms, it means a row creation, updating or deletion events.

    当多个代码段对同一模型实例事件感兴趣时,最好使用信号。 为了用更简单的术语理解模型实例事件,这意味着创建行,更新或删除事件。

    如何使用信号 (How to use Signals)

    While there are many ways to use signals, my favourite way is to use the ‘@receiver’ decorator.

    尽管有很多使用信号的方法,但我最喜欢的方法是使用'@receiver'装饰器。

    Here is an example

    这是一个例子

    Image for post
    signals.py
    signal.py

    This might seem a bit confusing right now if you are a beginner, but let me help you out here.

    如果您是初学者,现在可能看起来有些混乱,但是让我在这里为您提供帮助。

    The receiver decorator her tells the code that the function(‘notify_user’ here) is about to receive a signal(post_save signal in this case). Now there are many types of Django signals, post_save(django.db.models.signals.post_save) is one of it. Let’s go through some of the important signals separately.

    接收方装饰器她告诉代码该函数(此处为'notify_user')即将接收信号(在这种情况下为post_save信号)。 现在有许多类型的Django信号, post_save ( django.db.models.signals.post_save )是其中之一。 让我们分别浏览一些重要信号。

    1.使用post_save的技巧 (1. Tips to use post_save)

    As the name suggests, it is called just after the Django model save() function has done its job. The sender parameter here defines the Model from which we are trying to receive the signal. So now if I am to convert the above python code in English, I would say:

    顾名思义,它是在Django模型save()函数完成其工作之后调用的。 这里的sender参数定义了我们试图从中接收信号的模型。 因此,现在如果我要将上述python代码转换为英语,我会说:

    Call the function ‘notifiy_author’ after the istance of ‘ArticleComments’ is saved

    保存“ ArticleComments”的位置 ,调用函数“ notifiy_author”

    Whenever we use signals, we get to use some variables. One of those variables, as you can see in the above code snippet is ‘instance’. This is nothing but the instance of the model ArticleComments which is being saved. So if I want to fetch the author of the comment, I can easily use:

    每当我们使用信号时,我们都会使用一些变量。 如您在上面的代码片段中所见,这些变量之一是'instance' 。 这不过是正在保存的ArticleComments模型的实例。 因此,如果我想获取评论的作者,则可以轻松使用:

    instance.article.author
    Image for post

    Now a perk about using post_save signal is that it provides us with a variable named created. This is a flag, which returns True if this post_save signal is called when a new instance(or row) of a model was created.

    现在,有关使用post_save信号的好处是,它为我们提供了一个名为created的变量。 这是一个标志,如果在创建模型的新实例(或行)时调用此post_save信号,则返回True。

    Following points should be kept in mind while using post_save:1. There are no special signals like pre_create or post_create. Whenever we call Model function create(), it calls the save signals.2. You cannot modify the value of the any instance’s fields(for ex: ‘instance.comment’ here) inside post_save, without calling Django save() method again, which is not(never) a good practice to call inside a signal of the same model(Can you guess why?)

    使用post_save时应牢记以下几点:1。 没有像pre_create或post_create这样的特殊信号。 每当我们调用模型函数create()时,它都会调用保存信号。2。 您不能在post_save内修改任何实例字段的值(例如,此处为“ instance.comment”),而无需再次调用Django save()方法,这不是(永远) 在同一信号内调用的好习惯模型 (您能猜出为什么吗?)

    2.像专业人士一样使用pre_save (2. Use pre_save like a pro)

    Pre_save (django.db.models.signals.pre_save) is provoked just before the model save() method is called, or you could say model save method is called only after pre_save is called and done its job free of errors.

    Pre_save( django.db.models.signals.pre_save )是在调用模型save()方法之前引发的,或者可以说只有在调用pre_save并完成其工作而没有错误之后,才调用模型保存方法。

    We know how to notify the author when a new comment is posted(the same way you can create a signal on the creation of ArticleReaction too), but what if I want to notify the author when the reaction is modified? pre_save comes in handy for similar cases.

    我们知道如何在发布新评论时通知作者(也可以在创建ArticleReaction时创建信号的方式),但是如果我想在修改React后通知作者怎么办? pre_save在类似情况下非常有用。

    Image for post
    signals.py
    signal.py

    We do not get ‘created’ variable to use in pre_save. No worries, we have a workaround for that too.

    我们没有在pre_save中使用“创建”变量。 不用担心,我们也有解决方法。

    All the model instances(or rows) have an auto-generated primary key which is name ‘id’. This id is numerically incremented as instances of the model are created. But the ‘id’ can only be generated/assigned after the creation of the row. Hence in pre_save, if we try to access the instance.id before the instance(or row) is created, it will return us None. So the condition on line 10 in the above snippet is nothing but a replica of ‘created’ from post_save.

    所有模型实例(或行)都有一个自动生成的主键,名称为'id'。 创建模型实例时,此id会按数字递增。 但是“ id”只能在创建行生成/分配。 因此,在pre_save中,如果我们尝试在创建实例(或行)之前访问instance.id,它将返回None。 因此,以上代码段中第10行的条件仅是post_save中“ created”的副本。

    Image for post
    line 10
    第10行

    (Notice how I am using ‘row’ to refer an instance of a model. It will help you to have a clearer imagination of what’s happenning behind the scenes. Similarly, attributes/firelds can be referred with another term ‘column’)

    (请注意,我是如何使用“行”来引用模型实例的。这将帮助您更清楚地了解幕后发生的事情。类似地,属性/对象也可以用另一个术语“列”来引用)

    Our problem statement was to notify the author if the reaction is changed. Let’s try to backtrace it. To find if the reaction was changed, we need the current reaction and the previous reaction. If the current reaction and the previous reaction does not match, then it concludes that the reaction was changed and hence we need to notify the author about it. But how exactly can we get the previous and the current reactions? To understand that, we have to know one VERY IMPORTANT property about the variable instance in post_save and pre_save:

    我们的问题陈述是,如果React发生更改,则通知作者。 让我们尝试回溯它。 为了确定React是否发生变化,我们需要当前React和先前React。 如果当前React和先前React不匹配,则得出结论,React已更改,因此我们需要将其通知作者。 但是,我们究竟如何才能获得先前和当前的React呢? 要了解这一点,我们必须了解有关post_save和pre_save中的变量实例的一个非常重要的属性:

    The post_save’s instance has the attributes with values which are already saved in your model, but the pre_save’s instance has the attributes with values which are yet to be saved in your model.

    post_save实例的属性值已保存在模型中,而pre_save实例的属性值已保存在模型中。

    To make the above line more clearly, let’s take an example. Some user named ‘Ravi’ has already reacted with a ‘Like’. Ravi has a habit of reading everything twice. After reading the article again, he decided to change his reaction to ‘Love’.

    为了使以上内容更加清晰,我们来看一个例子。 一些名为“ Ravi”的用户已经做出了“赞”的React。 拉维有阅读两次所有内容的习惯。 再次阅读文章后,他决定将自己的React更改为“爱”。

    Image for post

    Let’s dive back inside our code again. Pre_save is called as soon as Ravi changed the reaction. Since the instance(or row) was already created, we move directly to the else condition in Line 14. Using the above-highlighted property, we can say that the variable ‘instance’ will have the new value ‘Love’ for its attribute ‘reaction’. Let’s name this modified variable ‘instance’ as ‘created’ (Line 15). Now we just need to get the old reaction. Remember that the ‘Love’ reaction has not been saved in our model yet(since we are still in pre_save). So what will we get if we try to get a model instance of ArticleReaction with the id provided by pre_save? We will get the instance with the reaction ‘Like’. Now let’s name this as ‘previous’(line 16). As we now have both old and new instances, we can easily compare these reactions and code are conditions accordingly.

    让我们再次跳回代码内部。 Ravi更改React后,将立即调用Pre_save。 由于已经创建了实例(或行),因此我们直接移至第14行中的else条件。使用上面突出显示的属性,我们可以说变量“ instance”为其属性“”具有新的值“ Love”React'。 让我们将此修改后的变量“实例”命名为“创建”(第15行)。 现在我们只需要得到旧的React。 请记住,“爱”React尚未保存在我们的模型中(因为我们仍处于pre_save状态)。 那么,如果我们尝试使用pre_save提供的ID来获取ArticleReaction的模型实例,将会得到什么呢? 我们将获得带有“ Like”React的实例。 现在,将其命名为“ previous”(第16行)。 由于现在有了新旧实例,我们可以轻松地比较这些React,并且代码相应地是条件。

    Image for post
    line 15 and 16
    第15和16行

    Since pre_save is called right before the model save() method, you can also modify the instance’s fields as per the requirement. For example, if we are using pre_save for ArticleComments and we want to check and remove any abuse words from comments before it is saved in our model, we can do it like this:

    由于pre_save在模型save()方法之前被调用,因此您还可以根据需求修改实例的字段 。 例如,如果我们在文章评论中使用pre_save,并且想要在注释中删除任何滥用词,然后再将其保存在模型中,则可以这样进行:

    if is_abuse(instance.comment):
    instance.comment = remove_abusive(instance.comment)

    Assuming that is_abusive and remove_abusive is your custom method. Also notice that we are not calling instance.save() after changing the instance.comment. Can you tell why?

    假设is_abusive和remove_abusive是您的自定义方法。 还要注意,在更改instance.comment之后,我们没有调用instance.save()。 你能说出为什么吗?

    3.其他信号 (3. Other Signals)

    There many more signals you can use, which you can find here, but this blog was just an attempt to give you the idea of how you can use signals effectively.

    您可以在这里找到更多可以使用的信号,但是此博客只是尝试向您提供如何有效使用信号的想法。

    在我们完成之前 (Before we finish)

    Even though signals come in handy when you want to perform actions behind the scenes, you have to be very careful about how you use it.

    即使您想在幕后执行操作时,即使信号会派上用场,您也必须非常谨慎地使用它。

    1. Do not compromise speed: putting too much load on pre_save or post_save signals might make the model save() method slow.

      不要牺牲速度 :在pre_save或post_save信号上增加过多的负载可能会使模型save()方法变慢。

    2. Lost in the loop: Calling the save() method for the sender model inside the post_save or pre_save will keep calling the signals repetitively.

      迷失在循环中:在post_save或pre_save内部调用sender模型的save()方法将继续重复调用信号。

    3. Remember the use cases: We use post_save when we are interested more in the creation of a model instance without modifying the values, while we use pre_save when we are more into the monitoring the change in model instance’s value, or if we are into modifying the instance’s attribute’s values ourselves.

      记住用例:当我们对模型实例的创建更感兴趣而不修改值时,我们使用post_save;而当我们更想监视模型实例的值的变化时,或者如果我们要修改模型时,则使用pre_save。实例属性的值本身。

    4. update() and save signals don’t get along: Django model ‘update()’ method does not invoke any kind of pre_save or post_save signals.

      update()和save信号不兼容:Django模型的update()方法不会调用任何pre_save或post_save信号。

    翻译自: https://medium.com/@singhgautam7/django-signals-master-pre-save-and-post-save-422889b2839

    展开全文
  • --save 和 --save-dev简述

    千次阅读 2022-04-24 16:37:58
    --save 和 --save-dev简述

    –save 和 --save-dev简述

    指定依赖项

    要指定项目所依赖的包,需要在package.json文件中列出要使用的包。这些包分为两种类型:

    "dependencies":您的应用程序在生产中需要这些包。
    "devDependencies":这些包仅用于开发和测试。
    

    在这里插入图片描述

    –save 和 --save-dev

    添加依赖项的更简单的方法是从命令行执行此操作,使用或 package.json标记npm install命令,具体取决于您希望如何使用该依赖项。–save 和 --save-dev。

    要向您 package.json的 dependencies中添加:

    npm install <package_name> --save
    

    要向您package.json的 devDependencies中添加:

    npm install <package_name> --save-dev
    

    总结

    使用--save装包,会使用dependencies这种方式,这种方式的应用程序在生产中需要这些包。

    使用--save-dev,会使用devDependencies这种方式,这些包仅用于开发和测试

    npm官网

    展开全文
  • Workbook.SaveAs方法

    千次阅读 2022-02-11 09:11:18
    Workbook.SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local) excel vba 保存...
  • Image.Save 方法

    千次阅读 2020-08-24 10:54:24
    Save(String, ImageCodecInfo, EncoderParameters) 使用指定的编码器和图像编码器参数,将该 Image 保存到指定的文件。 Save(Stream, ImageCodecInfo, EncoderParameters) 使用指定的编码器和图像编码器参数,将该...
  • jpa 的 save 方法

    千次阅读 2021-03-21 08:19:24
    scoreSummaryRepository.save(scoreSummary); } 后来潘老师评论说这样只会保存一个对象,之后的会更新。才突然想到这个问题,其实之前是有用到的 logger.info("保存"); CourseArrangement assertCourseArrangement ...
  • Spring-Data-Jpa 保存时save和saveAndFlush的区别 Jpa是我们经常用到的ORM框架,使用它可以快速便捷的操作数据库,那么它有一个保存方法,你肯定不会陌生,就是save方法和saveAndFlush,这两个方法可能会经常用到,...
  • IDEA 代码格式化插件Save Actions

    千次阅读 2022-04-20 01:37:31
    IDEA 安装Save Actions 插件 1、打开setting,找到Plugins选项(安装Save Action 插件(如果有就跳过这一步)) 检索:Save Actions 安装成功后,重新启动IDEA编辑器 2、打开setting,在other plugin 插件中找到...
  • vue npm install安装的命令,-save和-save-dev
  • PyTorch:模型save和load

    千次阅读 2020-10-28 23:06:25
    A common PyTorch convention is to save models using either a.ptor.pthfile extension. 保存加载整个模型(不推荐) 保存整个网络模型 (网络结构+权重参数) torch.save(model, 'net.pth')加载整个网络...
  • 表达式.SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local) 表达式 一个代表 ...
  • matlab中save用法

    千次阅读 2021-04-18 12:55:21
    用doc save就能得到save的用法说明其他的函数也是Save all variables from the workspace in binary MAT-file test.mat. Remove the variables from the workspace, and retrieve the data with the load function....
  • keras保存模型中的save()和save_weights()

    万次阅读 多人点赞 2019-01-23 16:38:23
    今天做了一个关于keras保存模型的实验...同样是h5文件用save()和save_weight()保存效果是不一样的。 我们用宇宙最通用的数据集MNIST来做这个实验,首先设计一个两层全连接网络: inputs = Input(shape=(784, )) ...
  • 如何在Python中生成save函数

    千次阅读 2021-02-03 09:51:10
    我想将doNothing()函数改为Save函数。我希望用户能够命名他在程序中写的文件,并将其保存在他想要的地方。在from tkinter import *# ********** Functions **********def doNothing():print("Ok, i won't!")# ******...
  • Unable to save settings: Failed to save settings. Please restart IntelliJ IDEA 问题解决 1.产生原因,错误的关闭idea造成 2.本人产生问题原因:自己作死模拟10W并发测试接口.然后电脑死机了…强制关机…idea挂了...
  • docker save 保存导出镜像

    千次阅读 2022-03-25 11:39:23
    m="新增app" -a="test" fce91102e17d tomcat save 保存(导出)镜像 # 把镜像打包成 .tar # -o 要保存路径.tar # > 要保存路径.tar # docker save 镜像id > /存储路径/xxx.tar docker save fce91102e17d>/root/tomcat....
  • numpy save & load

    千次阅读 2020-04-12 10:13:09
    numpy.save 保存一个数组到一个二进制的文件中,保存格式是.npy 参数介绍 numpy.save(file, arr, allow_pickle=True, fix_imports=True) file:文件名/文件路径 arr:要存储的数组 allow_pickle:布尔值,允许使用...
  • docker save与docker export的区别

    万次阅读 多人点赞 2017-09-25 20:29:36
    docker save和docker export都能导出镜像包,咋看起来区别似乎不大。本文就针对这个问题,试图搞清楚docker save和docker export的功能是什么?适用于什么应用场景? 本文的测试的Docker版本如下,不保证所有版本的...
  • model.save()保存了模型的图结构和模型的参数,保存模型的后缀是.hdf5。 model. save_weights ()只保存了模型的参数,并没有保存模型的图结构,保存模型的后缀使用.h5。 所以使用save_weights保存的模型比使用save...
  • pytorch中的torch.save()和torch.load()

    千次阅读 2021-10-28 06:50:38
     pytorch中torch.save()和torch.load()分别表示模型的存储和加载,具体相关的用法如下所示: torch.save(obj,f,pickle_module=pickle,pickle_protocol=DEFAULT_PROTOCOL,_use_new_zipfile_serialization=True) ...
  • Matlab工具使用(一):Save语法

    千次阅读 2019-02-22 14:42:22
    save 将工作区变量保存到文件中 全页折叠 语法 save(filename) save(filename,variables) save(filename,variables,fmt) save(filename,variables,version) save(filename,variables,version,'-no...
  • JPA中save方法

    千次阅读 2021-07-15 09:52:51
    今天在阅读代码的过程中,看到测试中的代码如下 User testSave3 = User.builder().name("testSave3... userDao.save(testSave3); log.debug("【testSave2.getId】 = {}",testSave3.getId()); Assert.assertNotNull(t
  • matlab saveas 分辨率

    千次阅读 2021-01-15 15:54:13
    选择保存形式 (fig,eps,jpeg,gif,png,bmp 等) ,缺点是另存为的图像清晰度......saveas 命令格式 Matlab 提供直接的 saveas 函数可以将指定 figure 中的图像或者 simulink 中的框图进行保存, 相当于【文件】中的...
  • gorm Save函数 使用注意点

    千次阅读 2022-02-18 09:49:58
    Save() 函数 — 替换 或者创建 根据where条件和传入结构体的主键进行查找 没有查找到,就会创建记录 查找到就会更新记录 如果结构体对应字段没有被赋值,在更新,或者创建时 ,就会以对应字段就会以零值更新或创建...
  • 使用方法1.[Easy Save3存储支持的类型](https://docs.moodkie.com/easy-save-3/es3-supported-types/)2.设置3.Keys, Paths and LocationsFilePlayerPrefsResourcesMemory5.加密6.保存并加载字符串和字节到文件7.保存...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,546,173
精华内容 618,469
关键字:

save